Home > Software design >  How to replace object of array when a condition is met
How to replace object of array when a condition is met

Time:11-04

I am trying to update an array with another array. The second array is dynamic and the point is only thing that would change. The order or indices of the elements are not important (not sequential)

arrayA = [
{name: 'John Doe', sport: 'soccer', point: 20},
{name: 'Jack Kim', sport: 'tennis', point: 10},
{name: 'Tiger Wood', sport: 'golf', point: 22},
{name: 'Lewis Hamilton', sport: 'F1', point: 30},
]

The arrayB may be another point values and maybe all or single at a time.

arrayB = [
{name: 'John Doe', sport: 'soccer', point: 50},
{name: 'Jack Kim', sport: 'tennis', point: 100},

]

The new array will look this for whatever occurrence.

newArray = [
{name: 'John Doe', sport: 'soccer', point: 50},
{name: 'Jack Kim', sport: 'tennis', point: 100},
{name: 'Tiger Wood', sport: 'golf', point: 22},
{name: 'Lewis Hamilton', sport: 'F1', point: 30}]

I am trying to update the arrayA by the ArrayB, as their indices may not be the same all the time. I was thinking to use .slice to remove where there is match and then push arrayB completely. I think this may be a bad programming idea. I am looking for how to optimize this approach.

NOTE: this is more like an algorithm to explain what I was thinking to do. I haven't tested it but I know there should an easy way out to resolve this.


let newArray = [];
arrayA.map(v => {
    if(v.sport === arrayB.sport) {
      index = arrayA.findIndex(v.sport)
      arrayA.slice(index);
       newArray = arrayA;
     }
});

newArray.push(arrayB)


CodePudding user response:

You could map over the first array, use the points of the player in the second array, if they were found, and default to the original points:

const arrayA = [
{name: 'John Doe', sport: 'soccer', point: 20},
{name: 'Jack Kim', sport: 'tennis', point: 10},
{name: 'Tiger Wood', sport: 'golf', point: 22},
{name: 'Lewis Hamilton', sport: 'F1', point: 30},
]

const arrayB = [
{name: 'John Doe', sport: 'soccer', point: 50},
{name: 'Jack Kim', sport: 'tennis', point: 100},
]

const result = arrayA.map(({ name, sport, point }) => ({
    name, sport,
    point: arrayB.find((p) => p.name === name && p.sport === sport)?.point ?? point,
}));

console.log(result);

References for syntax that may be strange:

  • Related