MadHatter
MadHatter

Reputation: 386

JavaScript forEach() method confusion

Using nodejs in Ubuntu. I've been reading the MDN docs for the JavaScript forEach() method. I understand there are other ways to do this, but I learn by doing; I'm trying to make the array copy a unique collection of the values in the arr array; no duplicates. I want to do this using the forEach() method.

The setup:

var arr = [1, 2, 3, 4, 4, 3, 2];
var copy = [];

So why does this work?

copy.includes(1); // returns false

While this doesn't?

arr.forEach(function(element, copy) {
 if (!copy.includes(element)) {
   copy.push(element);
 }
});

And here is the error:

TypeError: copy.includes is not a function
    at repl:2:11
    at Array.forEach (native)
    at repl:1:5
    at ContextifyScript.Script.runInThisContext (vm.js:23:33)
    at REPLServer.defaultEval (repl.js:339:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.onLine (repl.js:536:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:191:7)

Upvotes: 0

Views: 166

Answers (2)

Sanchit Patiyal
Sanchit Patiyal

Reputation: 4920

The second argument of forEach callback is the index, And by mentioning copy as a second argument, you are getting the index and not the array declare before. So what you are trying to do is 0.includes which actually is not a function. Removing the second argument will solve your problem

arr.forEach(function(element) {
 if (!copy.includes(element)) {
copy.push(element);
}
});

Upvotes: 1

Daniel
Daniel

Reputation: 18672

Try:

arr.forEach(function(element) {
 if (!copied.includes(element)) {
   copied.push(element);
 }
});

Second argument of forEach callback is index, not array you're trying to fill. Also, you referenced copy which is undefined, while correct variable named is copied according to your code example.

Edit

After you've edited your code you use name copy both for array and second argument of forEach callback (why the heck you need second argument of forEach callback - which by the way - is index, not "copy" - whatever copy you mean : P).

So, you get an error that Number.prototype doesn't have method called includes() which is true, because index is a Number.

To sum up:

arr.forEach(function(element) {
 if (!copy.includes(element)) {
   copy.push(element);
 }
});

Upvotes: 3

Related Questions