Home > Mobile >  Iterate through two array of arrays and run function on every arrays and create a new array with fun
Iterate through two array of arrays and run function on every arrays and create a new array with fun

Time:07-14

i have these two array of arrays (hi everyone, dont know why it doesnt print "hi everyone" at the start of paragraph)

MyArray1=[["jack", 0],["daniel", 2] ["sam", 1] ]

and this one MyArray2=[["jack", 0],["daniel", 10] ["sam", 2] ]

You see here there are sames values in both arrays, i would like to run a function that just adds two elements (it can be division also or substraction doesnt matter)

function myFunction(a, b) {
  return a   b;}

And returns a new array with this where the math is done

finalArray=[["jack", 0],["daniel", 12] ["sam", 3] ]

I know how to do it on two simple arrays but on array of arrays i'm lost.

Thanks !

CodePudding user response:

You can use map here to get the total as:

MyArray1.map(([str, num], index) => [str, num   MyArray2[index][1],])

When you map over an array then you have to pass a callback function that will receive arguments as:

Array.prototyep.map

callbackFn Function: that is called for every element of arr. Each time callbackFn executes, the returned value is added to newArray.

The function is called with the following arguments:

element: The current element being processed in the array.

index: The index of the current element being processed in the array.

array: The array map was called upon.

thisArg (Optional): Value to use as this when executing callbackFn.

So you can use index of current array and get the value from second array using same index

const MyArray1 = [
    ['jack', 0],
    ['daniel', 2],
    ['sam', 1],
];
const MyArray2 = [
    ['jack', 0],
    ['daniel', 10],
    ['sam', 2],
];

const result = MyArray1.map(([str, num], index) => [
    str,
    num   MyArray2[index][1]
]);
console.log(result);

CodePudding user response:

I have generalized upon the answer of @NullPointerException.

const MyArray1 = [
  ['jack', 0],
  ['daniel', 2],
  ['sam', 1],
];
const MyArray2 = [
  ['jack', 0],
  ['daniel', 10],
  ['sam', 2],
];


var add = function(a, b) {
  return a   b;
}

function apply_array(func, MyArray1, MyArray2) {
  const result = MyArray1.map(([str, num], index) => [
    str,
    func(num, MyArray2[index][1])
  ]);
  return result;
}

console.log(apply_array(add, MyArray1, MyArray2));

  • Related