Home > database >  How do I convert two different array into one single Array of Object in JavaScript [closed]
How do I convert two different array into one single Array of Object in JavaScript [closed]

Time:09-28

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:

  1. Turn arr2 into a Set so you can perform O(1) lookups
  2. Map arr1 into the result you want, using the Set to get true / 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());
  • Related