0

i have to update an element in array object based on a condition. currently i am using forEach and based on condition i am applying calculation in that element. i want to know the easiest way to updating the array without for loop below is my array

[{index:123,total:20,family:'mobile'},
{index:321,total:40,family:'mobile'},
{index:543,total:54,family:'mobile'}]

i want to update total with total*2 for an element with index '321'in the above array my array should look like below after executing logic

[{index:123,total:20,family:'mobile'},
{index:321,total:80,family:'mobile'},
{index:543,total:54,family:'mobile'}]

i am using below code

var selectedId = 321;
this.arrayList.forEach((element, indexval) => {
  if((element.index== selectedId){
    this.arrayList[indexval].total = element.total*2
  } 
});

can this be optimized so that i need not iterate the list

6
  • 1
    you need to find and then update it. so find does a loop until it is found Commented Apr 21, 2023 at 6:42
  • or you could have kept a Map with key as index and the object as value Commented Apr 21, 2023 at 6:43
  • unless you can get the index of the specific element from somewhere, you need to iterate the over array. You can add a break to exit the loop once you find the element. Commented Apr 21, 2023 at 6:48
  • 1
    @nullptr Suggesting a break in an implementation which currently uses forEach doesn't make too much sense, because you cannot break out of a forEach Commented Apr 21, 2023 at 6:53
  • const elem = this.arrayList.find(({index}) => index===321); if (elem) elem.total*=2 Commented Apr 21, 2023 at 7:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.