mav91
mav91

Reputation: 175

JavaScript array filter returns undefined

I'm trying to understand what rules apply to array mapping when using different syntax/method of writing a function.

    var MyArray = ["Item1", "Item2", "Item3", "Item4"]

function removeEveryOther(array){
    array.filter(function(value, index) {
        return index % 2 === 0;
    })
}

var Filtered = MyArray.removeEveryOther;
console.log(Filtered);

I want to remove every other element from an array using filter. For some reason the above returns undefined, why?

Upvotes: 1

Views: 2676

Answers (4)

palaѕн
palaѕн

Reputation: 73896

Firstly, you need to return the .filter() method result here like:

function removeEveryOther(array) {
  return array.filter(function(value, index) {
    return index % 2 === 0;
  })
}

Otherwise what you are doing is mainly returning undefined like:

function removeEveryOther(array) {}
console.log( removeEveryOther([]) )  //=> returns "undefined"

Then you need to properly call the removeEveryOther() function by passing the array like:

var Filtered = removeEveryOther(MyArray);
console.log(Filtered);

Demo (ES5):

var MyArray = ["Item1", "Item2", "Item3", "Item4"]

function removeEveryOther(array){
    return array.filter(function(value, index) {
        return index % 2 === 0;
    })
}

var Filtered = removeEveryOther(MyArray);
console.log(Filtered);

Demo (ES6):

var MyArray = ["Item1", "Item2", "Item3", "Item4"]
function removeEveryOther(array){
  return array.filter((value, index) => index % 2 === 0);
}

var Filtered = removeEveryOther(MyArray);
console.log(Filtered);

Upvotes: 1

Dmytro Cheglakov
Dmytro Cheglakov

Reputation: 744

Try this.

const MyArray = ['Item1', 'Item2', 'Item3', 'Item4'];

const removeEveryOther = array =>
  array.filter((value, index) => index % 2 === 0);

const Filtered = removeEveryOther(MyArray);
console.log(Filtered);

Upvotes: 0

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6390

According to MDN Array.prototype.filter creates a new array with all elements that pass the test implemented by the provided function.

You have to pass a callback function as the first argument of the filter.

Your code should look like this

var MyArray = ["Item1", "Item2", "Item3", "Item4"];
var filtered = MyArray.filter((item, index) => index % 2 === 0);

console.log(filtered);

Upvotes: 1

Naseh Badalov
Naseh Badalov

Reputation: 344

First, you need to return your filtered array like this:

return array.filter(function(value, index) {
        return index % 2 === 0;
})

Second, when you call your function you need to call it like this:

var Filtered = removeEveryOther(MyArray);

Overall, your code should look like this:

var MyArray = ["Item1", "Item2", "Item3", "Item4"]

function removeEveryOther(array){
    return array.filter(function(value, index) {
        return index % 2 === 0;
    })
}

var Filtered = removeEveryOther(MyArray);
console.log(Filtered);

Upvotes: 1

Related Questions