forEach() and Apply() methods for two dimensional array in JavaScript
Solution 1
First, calcMe
doesn't seem to return a function, so you can't pass its return value to forEach
.
I'm guessing you want something like
var arr = [
[1, 5, 4],
[8, 5, 4],
[3, 4, 5],
[1, 2, 3]
]
function calcMe(a, b, c) {
var pre = document.getElementById('pre')
pre.innerHTML += 'calcMe arguments: ' + a +","+ b +","+ c + "<br/>";
}
arr.forEach(function(el, index) {
// Could also use `arr[index]` instead of el
calcMe.apply(this, el);
});
<pre id='pre'></pre>
For a fancier version, you can bind Function.prototype.apply
to emulate creating a function like I did above.
Solution 2
apply
calls a function immediately, so you can't use it directly because forEach
expects a function reference. However, you can use bind
on apply
to achieve what you want:
arr.forEach(Function.apply.bind(calcMe, void 0));
The second argument will be the this
value. You can provide whatever value instead of void 0
.
var arr = [[1,5,4],[8,5,4],[3,4,5],[1,2,3]];
function calcMe(a,b,c){
document.querySelector('pre').textContent += [a,b,c] + '\n';
}
arr.forEach(Function.apply.bind(calcMe, void 0));
<pre></pre>
Solution 3
You need to provide a function for .forEach
. The function will be run over each element of your main array.
Depending on what calcMe
does, you might need to provide the right context for it in calcMe.apply
. The first agrument of .apply
is the context (this
keyword in the function). I just put null
, but you can pass what works for you.
var arr = [[1,5,4], [8,5,4], [3,4,5], [1,2,3]];
function calcMe(a,b,c){
console.log(a, b, c);
}
arr.forEach(function (params) {
calcMe.apply(null, params);
})
If you are willing to use ES6, you can use arrow functions and spread operator:
arr.forEach(params => calcMe(...params));
Solution 4
If you're interested in ECMAScript 6, here is the fastest and most elegant solution.
'use strict';
let arr = [
[1, 5, 4],
[8, 5, 4],
[3, 4, 5],
[1, 2, 3]
];
function calcMe(a, b, c) {
document.querySelector('p').innerHTML += `${a},${b},${c}<br>`;
}
for (let item of arr) {
calcMe(...item);
}
// Or
arr.forEach(item => calcMe(...item));
<p></p>
Solution 5
You can provide a lambda function
arr.forEach((u)=>{console.log(calcMe.apply(null, u))});
If you don't need to access object context, bind null
to the first argument should be fine. Otherwise, bind the object you desire.
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
I have an array whose elements are also arrays, each containing three elements. I want to call the
function calcMe(a,b,c){...}
for each of the elements of my main array usingforEach()
method, but I got really confused and don't know how to get it to work.arr = [[1,5,4], [8,5,4], [3,4,5], [1,2,3]] function calcMe(a,b,c){...} arr.forEach(calcMe.Apply(-----, -----));
How do I pass each of the inner array's elements as arguments to my function using
Apply()
?