Search code examples
javascriptarraysecmascript-5

Javascript filter values from array


I have an array of arrays and each of those arrays contain two elements. How can I return the second element from array by filtering the first element?

For example I have the following array and my function should return the second element from each sub-array where the first item is 8:

var array = [[8, 'first'], [8, 'second'], [1, 'empty'], [8, 'third'], [9, 'empty']];

Expected result: ['first', 'second', 'third']

This is what I've implemented so far, but it returns both elements instead of just the second one from each array with a match...

var array = [[8, 'first'], [8, 'second'], [1, 'empty'], [8, 'third'], [9, 'empty']];
var result = array.filter(function(item){
  if(item[0] == 8) {
    return item[1];
  }
});
console.log(result);


Solution

  • You could filter with the condition and then you need to map only the part, you want.

    In a single loop it is only possible with Array#reduce, because here you can manipulate the value for the result set.

    Array#filter returns the original item of the array, without changing something.

    The filter() method creates a new array with all elements that pass the test implemented by the provided function.

    For filtering, the callback needs to return a value which is interpreted as boolean, that means, every truthy value (like an object, array, or any not zero number, etc) takes the item for the result set.

    If you like to use only a part of the inner array and the part is a truty value, then filtering works, but it does not take the return value, because it is not made for that.

    var array = [[8, 'first'], [8, 'second'], [1, 'empty'], [8, 'third'], [9, 'empty']],
        result = array.filter(function(item){
            return item[0] === 8;
        }).
        map(function (a) {
            return a[1];
        });
    
    console.log(result);