noclist
noclist

Reputation: 1819

Replace a for loop with an Array map()

I have a for loop:

for (let i = 0; i < this.outputList.length; i++) {
  this.outputList[i].checked = this.selectedOutputs.includes(i);
}

Is it posssible to replace this with an array.map? I want to set the 'checked' property of items in the outputList to true if it's index exists in the selectedOutputs array. I can't wrap my head around how this would look using a map function.

Upvotes: 0

Views: 1636

Answers (3)

technophyle
technophyle

Reputation: 9128

You can do it like this:

this.outputList = this.outputList.map((item, i) => ({
  ...item,
  checked: this.selectedOutputs.includes(i),
}));

This will create a new array object from the old array, so it doesn't do the exact same thing. As others mentioned, it's best to use a for iteration in case you shouldn't create a new array object.

Upvotes: 1

Sifat Haque
Sifat Haque

Reputation: 6057

Actually i think forEach is a good match for your purpose. Here you can check the same implementation using forEach.

  this.outputList.forEach((outputList, i) => {
    outputList.checked = this.selectedOutputs.includes(i);
  })

Upvotes: 0

Bergi
Bergi

Reputation: 664297

No, since you are trying to mutate the objects in the outputList instead of building a completely new list, you should not use map. If you just don't like for (let i=0; i<length; i++) loops, you can use for … of:

for (const [i, output] of this.outputList.entries()) {
  output.checked = this.selectedOutputs.includes(i);
}

However, depending on the structure of your selectedOutputs array and assuming that .checked was initialised with false for every output, there might be an even better (and more efficient) approach:

for (const i of this.selectedOutputs) {
  this.outputList[i].checked = true;
}

Upvotes: 3

Related Questions