I've two array....
arr1 = ['a', 'b', 'c', 'd']
arr2 = ['b', 'd']
both array has some string value... I want to create a new Array of object from those array.. if arr1 is large array.. and arr2 is could be equal as arr1 or could be empty array at all.
If string of arr1 exist on arr2 then output object will be true or if it doesn't exist then output will be false..
Output:
result = [{'a': false}, {'b': true}, {'c': false}, {'d': true}]
CodePudding user response:
- Turn
arr2
into a Set so you can perform O(1) lookups - Map
arr1
into the result you want, using theSet
to gettrue
/false
values
const arr1 = ['a', 'b', 'c', 'd']
const arr2 = ['b', 'd']
const lookup = new Set(arr2)
const result = arr1.map(key => ({
[ key ]: lookup.has(key)
}))
console.log(result)
.as-console-wrapper { max-height: 100% !important; }
CodePudding user response:
function foo() {
const arr1 = ["a", "b", "c", "d"];
const arr2 = ["b", "d"];
const result = [];
for (const item of arr1) {
result.push({ [item]: arr2.includes(item) });
}
return result;
}
console.log(foo());