1

I've an array like this:

const myArray = ['Item1', 'Item3', 'Item5'];

And an object list like that:

ObjectsList: {
    Item1: ["A", "B", "C"],
    Item2: ["A", "D", "E"],
    Item3: ["B", "E", "C", "G"],
    Item4: ["B", "C", "R"],
    Item5: ["D"],
    Item6: ["F", "D", "E"],
    Item7: ["A", "E", "L", "M"],
}

I want to get the values of all the keys with the same name of my array elements and push them into a new array without duplicate elements.

In the case of my provided example I want to get the Item1, Item3, Item5 keys values and push them in a new array avoiding duplicates. The result should be that: [A, B, C, E, G, D]

Which is the best way to do that in JavaScript? Thanks in advance.

1 Answer 1

5

You can .flatMap() your myArray to an array of characters from the ObjectsList, and then use a Set to remove the duplicate characters. Lastly, you can use the spread syntax (...) to convert the set into an array:

const objectsList = { Item1: ["A", "B", "C"], Item2: ["A", "D", "E"], Item3: ["B", "E", "C", "G"], Item4: ["B", "C", "R"], Item5: ["D"], Item6: ["F", "D", "E"], Item7: ["A", "E", "L", "M"], };
const myArray = ['Item1', 'Item3', 'Item5'];

const res = [...new Set(myArray.flatMap(k => objectsList[k]))];
console.log(res);

If you can't support .flatMap(), you can use a regular .map(), and then use .concat() to perform the flattening:

const objectsList = { Item1: ["A", "B", "C"], Item2: ["A", "D", "E"], Item3: ["B", "E", "C", "G"], Item4: ["B", "C", "R"], Item5: ["D"], Item6: ["F", "D", "E"], Item7: ["A", "E", "L", "M"], };
const myArray = ['Item1', 'Item3', 'Item5'];

const res = [...new Set([].concat(...myArray.map(k => objectsList[k])))];
console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.