-3

How can I rewrite this nested loop in ES6 and have it in one line ?

const fruits = [ { id: 1, name: "orange"},{ id: 3, name: "apple"},{ id: 4, name: "grape"}]
const selectedFruits = [ "2", "3" ]
  
let fruitsArr= [];

fruits.forEach(fruit => {
  selectedFruits.forEach(selected => {
    if (selected == fruit.id) {
      fruitsArr.push(fruit.name)
    }
  })
})

console.log(fruitsArr)
  

3
  • 1
    That is ES6, and putting it on one line would just make it harder to read. Commented Jan 30, 2020 at 9:20
  • 1
    Any Javascript code can be squashed onto one line Commented Jan 30, 2020 at 9:21
  • Just a logic problem. let fruitsArr = fruits.filter(f => selectedFruits.indexOf(f.id + "") > 0).map(f => f.name); Commented Jan 30, 2020 at 9:22

2 Answers 2

0

You could filter the array and check with includes by changing selectedFruits to an array of number.

const
    fruits = [{ id: 1, name: "orange" }, { id: 3, name: "apple" }, { id: 4, name: "grape" }],
    selectedFruits = [2, 3],
    fruitsArr = fruits.filter(({ id }) => selectedFruits.includes(id));

console.log(fruitsArr);

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

Comments

0

With reduce:

const fruits = [ { id: 1, name: "orange"},{ id: 3, name: "apple"},{ id: 4, name: "grape"}]
const selectedFruits = [ "2", "3" ]
const fruitsArr = fruits.reduce((p, c) => (selectedFruits.includes(String(c.id)) && p.push(c), p), [])
console.log(fruitsArr)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.