2

I have two different array parent and child relational array and combine single array.

this is parent array:- const cat = ['a','b','c']; this is Child array:- const sub =[{name:'cloth',cat:['a','b']},{name:'feshion',cat:['b','a']}]

the output Combine Two array and make single array, I am using map and filter method, It doesn't work the output should be like this const parent =[{name:'a',sub:['cloth','feshion']},{name:'b',sub:['cloth','feshion']},{name:'c',sub:[]}]

Please help me, and Please give me any Idea

1
  • So loop over the parent with map and combine. Commented Apr 23, 2020 at 15:27

1 Answer 1

3
const result = cat.map(name => ({name, sub: sub.filter(s => s.cat.includes(name)).map(s => s.name)}));

produces:

[
   { "name": "a", "sub": ["cloth", "feshion"] },
   { "name": "b", "sub": ["cloth", "feshion"] },
   { "name": "c", "sub": [] }
]

Here's an expanded version of that line, easier to follow:

const result = cat.map(catName => {
   const subs = sub
      .filter(s => s.cat.includes(catName))
      .map(s => s.name);

   return {name: catName, sub: subs};
});

Run the code:

const cat = ['a','b','c'];
const sub =[{name:'cloth',cat:['a','b']},{name:'feshion',cat:['b','a']}];
const result = cat.map(name => ({name, sub: sub.filter(s => s.cat.includes(name)).map(s => s.name)}));
console.log(result);

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.