简体   繁体   中英

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]]);

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.

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]

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]])); 

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;
}

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]])); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM