Rave Sean
Rave Sean

Reputation: 131

Javascript filter function not returning array

function to return array of largest elements from each sub array


function largestOfFour(arr) {
      var max = 0;
      var newarr = [];
      newarr = arr.filter(function(elem) {
          max= 0;
          for(var i=0;i<elem.length;i++) {
            if(max<elem[i]) {
              max = elem[i];
            }
          }  
          return max;
        });
      return newarr;
    }

    largestOfFour([[4, 5000, 1, 3], [13, 27, 18, 26], [3, 35, 37, 39], [1000, 1001, 857, 1]]);

Upvotes: 1

Views: 7176

Answers (5)

Nina Scholz
Nina Scholz

Reputation: 386550

For completeness a solution in a line in ES6 with Array#map, Math.max and a spread syntax ....

const largestOfFour = array => array.map(a => Math.max(...a));

console.log(largestOfFour([[4, 5000, 1, 3], [13, 27, 18, 26], [3, 35, 37, 39], [1000, 1001, 857, 1]]));

Upvotes: 1

Wildsky
Wildsky

Reputation: 522

As erictgrubaugh said, Filter does not work like that,here is the document for you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

var filtered = [12, 5, 8, 130, 44].filter(function(val){
  return val >= 10;
});
// filtered is [12, 130, 44]

Upvotes: 1

anshulk
anshulk

Reputation: 458

filter won't do what you're trying to do. It just chooses if the element will be accepted or not.

What you need is map. It performs an operation on each element of array.

Here's a solution -

function largestOfFour(arr) {
  
      var newarr = [];
      newarr = arr.map(function(elem){
        return Math.max(...elem);
      });
      return newarr;
    }

console.log(largestOfFour([[4, 5000, 1, 3], [13, 27, 18, 26], [3, 35, 37, 39], [1000, 1001, 857, 1]]));

Upvotes: 0

ankur kushwaha
ankur kushwaha

Reputation: 478

You can use the below program to find the larget element in all subarrays

function largest(arr){
    var out=[];
    for(var i=0;i<arr.length;i++){
        var max=Number.MIN_VALUE;
        for(var j=0;j<arr[i].length;j++){
            max=Math.max(max,arr[i][j]);
        }
        out.push(max);
    }
    return out;
}

Upvotes: 0

erictgrubaugh
erictgrubaugh

Reputation: 8847

That's not really how the filter function works. The function you pass into filter needs to return a Boolean: true if the given element should remain in the resulting Array, and false if it should be removed. Since you are returning max, which is a Number, any non-zero value will be interpreted as true, and so the element will remain in the Array.

You might try instead writing a max function that sorts an Array and grabs the first element (or last, depending on sort direction), then map-ing that function over your Array of four Arrays.

Upvotes: 4

Related Questions