0

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.

6
  • 2
    Not sensibly. I avoid indexed for loops whenever I can, but I think what you're doing currently is just fine. Commented Nov 25, 2020 at 20:34
  • map returns an array and i don't think that's what you are looking for Commented Nov 25, 2020 at 20:35
  • 1
    .map is when you want a new array based on a previous one. Since it doesn't seem you're iterating one array and producing another from it, then .map is not a good choice. Commented Nov 25, 2020 at 20:36
  • 1
    You can use forEach for this. But map isn't a good match Commented Nov 25, 2020 at 20:36
  • 1
    @noclist please check my reply. I've shared the forEach implementation there Commented Nov 25, 2020 at 20:40

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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);
  })

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.