Best Way To Compare An Array Of Strings To An Array Objects With String Properties?
I have an array of object, within those objects is a name property. const objArr = [ { name: 'Avram' }, { name: 'Andy' } ]; I’m collecting an array of strings from an outside sou
Solution 1:
like this
const objArr = [ { name: "Avram" }, { name: "Andy" } ];
const strArr = [ "Avram", "Andy", "Brandon" ];
const names= objArr.map(x => x.name);
strArr.forEach(str => {
if (! names.includes(str) ) {
objArr.push({name: str});
}
});
console.log(objArr);
Solution 2:
functionfillMissing(arr, names) {
names.forEach(name => { // for each name in namesif(arr.every(obj => obj.name !== name)) { // if every object obj in the array arr has a name diferent than this name (this name doesn't exist in arr)
arr.push({name}); // then add an object with that name to arr
}
});
}
const objArr = [ { name: "Avram" }, { name: "Andy" } ];
const strArr = [ "Avram", "Andy", "Brandon" ];
fillMissing(objArr, strArr);
console.log(objArr);
Solution 3:
Map
objArr
to same structure as strArr
. Then concat
the 2 arrays. Run it through a Set
to remove duplicates, then remap
to correct array of object
const objArr = [ { name: "Avram" }, { name: "Andy" }, { name: "John"} ];
const strArr = [ "Avram", "Andy", "Brandon" ];
const res = Array.from(newSet(objArr.map(i=>i.name).concat(strArr))).map(i=>({name:i}))
console.log(res);
Solution 4:
const objArr = [ { name: "Avram" }, { name: "Andy" } ];
const strArr = [ "Avram", "Andy", "Brandon" ];
const objNamesArr = objArr.map((obj) => obj.name)
strArr.forEach((ele) => objNamesArr.indexOf(ele) == -1 && objArr.push({name:ele}))
console.log('objArr', objArr);
console.log('strArr', strArr);
Post a Comment for "Best Way To Compare An Array Of Strings To An Array Objects With String Properties?"