Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add to a value to a specific 2 dimensional array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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],
]

>Solution :

  • 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading