Home > database >  How to add to a value to a specific 2 dimensional array
How to add to a value to a specific 2 dimensional array

Time:01-23

I was wondering the best way to do this in javascript (ES6).

So I have a 2 dimensional array like so:

const two_dimensional_array = [
   [33000, 100],
   [33500, 200],
]

I now have another 2 dimensional array like so:

const another_array = [
 [33500, 1300]
]

and I want it to find the the first value from another_array in two_dimensional_array and then add the 2nd value to it. So the end result of two_dimensional_array would be like:

const two_dimensional_array = [
   [33000, 100],
   [33500, 1500],
]

CodePudding user response:

  • Create a Map from another_array where the key is the first number of the pair and the value is the second number.
  • Using Array#forEach, iterate over two_dimensional_array and try to check if there's a number to add (0 otherwise).

const 
  two_dimensional_array = [ [33000, 100], [33500, 200] ],
  another_array = [ [33500, 1300] ];

const map = new Map(another_array);

two_dimensional_array.forEach(arr => arr[1]  = map.get(arr[0]) ?? 0);

console.log(two_dimensional_array);

  •  Tags:  
  • Related