Reputation: 573
I have two arrays One 2D and another 1D.
My 2D array has many rows and columns for example:-
My 2D array has arr1 = [[a,b....9],[s,c....12],[x,y....14]] //and so on
My 1D array has arr2 = [3,2,6] // and so on
Now I want to multiply elements of the lastrow of my 2Darr
with consecutive 1Darr
and divide it by 2
then push the result at the last of the 2D array.
(9*3)/2
=13.5
(12*2)/2
=12
(14*6)/2
= 42
Now my New array should look like this newarr = [[a,b....9,13.5],[s,c....12,12],[x,y....14,42]] // and so on.
Upvotes: 0
Views: 52
Reputation: 4519
arr1 = [["a","b",9],["s","c",12],["x","y",14]],
arr2 = [3,2,6]
arr2.map((x,i)=>{arr1.map((y)=>{i===arr1.indexOf(y)?y.push((x*y[y.length-1])/2):null})})
console.log(arr1)
Upvotes: 1
Reputation: 386700
You could map the new arrays with the wanted new last value.
const
arr1 = [["a", "b", 9], ["s", "c", 12], ["x", "y", 14]],
arr2 = [3, 2, 6],
result = arr1.map((a, i) => [...a, a[a.length - 1] * arr2[i] / 2]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2
Reputation: 6749
You could just use reduce function to modify the contents of the array on the go and return the new parsed array
const arr1 = [["a","b",9],["s","c",12],["x","y",14]]
const arr2 = [3,2,6]
const result = arr1.reduce((results, element, index) => {
return [
...results, // push the rest of the results onto the new array
[
...element, // keep all the current items of the element (the 1d array)
element[element.length-1]*arr2[index]/2 // add new element, by querying the last element of the array and the appropriate index of the second array
]
]
},[] /*initially result being an empty array*/);
console.log(result)
Upvotes: 1