1

I'm trying to retrieve the array that has value within another array using filter method. So for instance, from this

[[], [{name:"shop", price: 48}],[]] 

to this

[{name:"shop", price: 48}]

From console.log below I get {name:"shop", price: 48}, but when I return v, I get whole thing back--> [[], [{name:"shop", price: 48}],[]]

What am I missing?

const a = [[], [{name:"shop", price: 48}],[]]

const output = a.map((value) => {
  return value.filter((v) =>{
    console.log(v)
    return v
  })
})
console.log(output);

3
  • Your map function does nothing except cloning your initial array, so what do you expect? Commented Oct 15, 2020 at 0:51
  • What if several arrays are non-empty, what do you you expect in those cases? Commented Oct 15, 2020 at 0:56
  • If you want to filter out empty arrays, then apply such filter. Commented Oct 15, 2020 at 0:56

2 Answers 2

2

Are you looking for this?

const a = [[], [{name:"shop", price: 48}],[]]

const [ output ] = a.filter(v => v.length); // will filter out empty arrays

console.log(output);

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

Comments

1

My solution of joining subarrays into one array:

const a = [[], [{name:"shop", price: 12}], [{name:"shop", price: 34}]];

let res = [];
a.forEach((aItem) => res = res.concat(aItem));

console.log(res);

Output

[ { name: 'shop', price: 12 }, { name: 'shop', price: 34 } ]

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.