1

I have following array of string used in select element (multi select) options.

let array = ["one", "two", "three"];

Also I have following Object.

{ "one" : ['apple','orange','banana'], "two" : ['cucumber','onion'], "three" : ['potato','radish','carot']};

I select one & two and I want to combine ['apple','orange','banana'] and ['cucumber','onion'] in another select dropdown.

2
  • What is the expected output? Commented Aug 3, 2021 at 22:08
  • ['apple','orange','banana','cucumber','onion'] Commented Aug 3, 2021 at 22:10

2 Answers 2

1

You can use Array#reduce in conjunction with Array#concat.

let chosen = ['one', 'two'];
let obj = { "one" : ['apple','orange','banana'], "two" : ['cucumber','onion'], "three" : ['potato','radish','carot']};
const res = chosen.reduce((acc, curr)=>acc.concat(obj[curr]), []);
console.log(res);

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

Comments

0

Use Array#map to iterate through the array and get the corresponding array in the object and Array#flat to flatten the result:

let array = ["one", "two"];
let obj = {
  "one": ['apple', 'orange', 'banana'],
  "two": ['cucumber', 'onion'],
  "three": ['potato', 'radish', 'carot']
};
const result = array.map(e => obj[e]).flat();
console.log(result);

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.