Add if not already in list
For a list of simple values, it's a one-liner...
[...new Set([...someArray, someElement])]
JavaScript Usage:
var myArray = ['bill','bob']
var alreadyIn = [...new Set([...myArray, 'bob'])] // ['bill','bob']
var notAlreadyIn = [...new Set([...myArray, 'peter'])] // ['bill','bob','peter']
TypeScript ext (note include vs includes):
interface Array<T> {
include(element: T): Array<T>
}
Array.prototype.include = function (element: any): any[] {
return [...new Set([...this, obj])]
}
...but for objects, it's more complicated
[...new Set([...someArray.map((o) => JSON.stringify(o)),
JSON.stringify(someElement)]).map((o) => JSON.parse(o))
TypeScript ext to handle anything:
Array.prototype.include = function (element: any): any[] {
if (element && typeof element === 'object')
return [
...new Set([
...this.map((o) => JSON.stringify(o)),
JSON.stringify(element),
]),
].map((o) => JSON.parse(o))
else return [...new Set([...this, element])]
}