Home > Mobile >  Multiply to arrays
Multiply to arrays

Time:11-10

I have two arrays and need to multiply, ex 4.56… with 0.134. It can be pushed to the second array, it can also be added to a new.

First array:

[[2022-09-01T00:00:00, 4.56255004875], [2022-09-01T01:00:00, 4.50295013375], [2022-09-01T02:00:00, 4.52136261], [2022-09-01T03:00:00, 4.46261261], [2022-09-01T04:00:00, 4.6035501100000005], [2022-09-01T05:00:00, 4.95328735375]

Second array

[[0.134], [0.132], [0.126], [0.129], [0.128], [0.145], [0.495], [1.837], [0.683], [0.125], [0.124], [0.128], [1.148], [0.39], [0.272], [0.479], [0.439]

Trying googlen answers, with no luck.

CodePudding user response:

I've shown 2 ways of doing it. Array.map() and Array.forEach(). I simply changed your dates to strings for the example.

If I had done it the other way around a.forEach() first then a.map(), the values in a would have been modified and the factor applied twice.

function multArray() {
  let a = [["2022-09-01T00:00:00", 4.56255004875], 
           ["2022-09-01T01:00:00", 4.50295013375], 
           ["2022-09-01T02:00:00", 4.52136261], 
           ["2022-09-01T03:00:00", 4.46261261], 
           ["2022-09-01T04:00:00", 4.6035501100000005], 
           ["2022-09-01T05:00:00", 4.95328735375]];
  
  let b = [[0.134], [0.132], [0.126], [0.129], [0.128], [0.145]];

  console.log("lets make a copy");
  let c = a.map( (row,i) => {
      let d = [row[0],row[1]]; // make a copy
      d[1] =  d[1]*b[i][0];
      return d;
    }
  );
  console.log(c);

  console.log(("now lets modify a"))
  a.forEach( (row,i) => row[1] = row[1]*b[i][0] );
  console.log(a);  // a is changed
}

6:39:41 AM  Notice  Execution started
6:39:44 AM  Info    lets make a copy
6:39:44 AM  Info    [ [ '2022-09-01T00:00:00', 0.6113817065325001 ],
  [ '2022-09-01T01:00:00', 0.594389417655 ],
  [ '2022-09-01T02:00:00', 0.56969168886 ],
  [ '2022-09-01T03:00:00', 0.57567702669 ],
  [ '2022-09-01T04:00:00', 0.5892544140800001 ],
  [ '2022-09-01T05:00:00', 0.71822666629375 ] ]
6:39:44 AM  Info    now lets modify a
6:39:44 AM  Info    [ [ '2022-09-01T00:00:00', 0.6113817065325001 ],
  [ '2022-09-01T01:00:00', 0.594389417655 ],
  [ '2022-09-01T02:00:00', 0.56969168886 ],
  [ '2022-09-01T03:00:00', 0.57567702669 ],
  [ '2022-09-01T04:00:00', 0.5892544140800001 ],
  [ '2022-09-01T05:00:00', 0.71822666629375 ] ]
6:39:42 AM  Notice  Execution completed

Reference

CodePudding user response:

Another way to do this is using for...of loop:

const arr_1 = [
  ['date_1',1],
  ['date_2',2],
  ['date_3',3]
];
const arr_2 = [[4],[5],[6]];

for (const [i,row] of arr_1.entries()) {
  arr_1[i][1] = row[1] * arr_2[i][0];
}

console.log(arr_1)

// Log:
// [
//  ["date_1", 4],
//  ["date_2",10],
//  ["date_3",18]
// ]

  • Related