-4

I have 2 arrays that both need to run forEach.

[267, 418, 568].forEach((item, idx) => item * 17 + idx)
[123, 234, 345].forEach((item, idx) => item * 17 + idx)

To reduce repetition, I'd like to replace the callback with an external function.

something like

const otherFunc = (item, idx) => {
    return item * 17 + idx
}

[123, 234, 345].forEach(otherFunc(item, idx))

What's the syntax for doing such?

monsto
  • 1,118
  • 1
  • 12
  • 21
  • 3
    don't call it just pass it `[123, 234, 345].forEach(otherFunc);` – pilchard Nov 10 '21 at 22:53
  • `forEach` doesn't return anything so you can't use the `[].forEach` syntax to change the array elements. Do you want `map` instead to create a new array? – Andy Nov 10 '21 at 23:09
  • @Andy No, I do not need `map`. The content of the post was for illustration purposes only. The main point was the syntax of using an external function as a callback. – monsto Nov 10 '21 at 23:16
  • But your `forEach` is trying to return a value, and that's not how that method works. Did you just want to log something to the console? – Andy Nov 10 '21 at 23:18
  • @Andy That's beside the point of the syntax question. – monsto Nov 10 '21 at 23:20
  • 1
    No, really, it's not. What are you trying to do in your `forEach`? – Andy Nov 10 '21 at 23:21

2 Answers2

2

You can use this

function loopItem(item, index) { 
  return item * 17 + index;
}

[267, 418, 568].forEach(loopItem);
[123, 234, 345].forEach(loopItem);
Vasim Hayat
  • 687
  • 8
  • 14
  • You should probably test this. – Andy Nov 10 '21 at 23:02
  • here is jsfiddle link *https://jsfiddle.net/hy3u1web/1/* – Vasim Hayat Nov 10 '21 at 23:08
  • But how does that update the original array which is what I assume the OP wants? – Andy Nov 10 '21 at 23:09
  • @Andy Your assumption is getting into the weeds. I didn't ask about modifying the original array, nor a return or map. I asked about a specific syntax. This response answers that question. – monsto Nov 10 '21 at 23:22
  • You did ask about a return because _your question involves a return_ which is why I'm questioning whether or not you know how `forEach` works. I'm not trying to be mean. It's just not clear what you want to achieve. – Andy Nov 10 '21 at 23:24
  • @Andy The code in the post was for an example, quickly typed. What I wanted to achieve was knowing the syntax of calling an external function for a callback. The question, ***as stated at the bottom of the post***, was clear to the 2 people that posted answers to that clear question. Thanks and have a good rest of your day! – monsto Nov 10 '21 at 23:28
0

You need to pass your function inside forEach directly(without executing)

[].forEach(someFunc);
Eugene
  • 96
  • 1
  • 6