Search code examples
javascriptarraysfiltersub-array

Return arrays within subarrays by length of greater than or less than 3 using filter


Hi I'm trying to implement the array filter property to sort out subarrays that are greater than and less than 3 with two seperate functions. I'm at a loss in terms of getting any further in correcting my functions. Could someone help and please explain why I'm getting the current results.

var subarrays = [
    [1,2,3],
    ['a','b','c','d','e'],
    ['hippopatamus', 'zebra', 'crocodile','lion'],
    [false, 2]
];

var greaterThan3 = function(array){ 
    for(var i = 0; i < array.length; i ++){
        if(array[i].length > 3) {
            return array[i];
        } else {
            return false;
        }
    }
};

var lessThan3 = function(array){
    var arr = [];
    for(var i = 0; i < array.length; i ++){
        if(array[i].length < 3){
            arr.push(array[i]);
        } else {
            return false;
        }
    }
    return arr;
};

When I return greater than, only the animal names show up. It seems that the length only refers to the length of the words and not the length of the array itself. How do I target the length of the array. With the less than I only get the single letters. Again I'm looking at the length of the array itself and not it's contents. Thanks.


Solution

  • The reason why you are only getting animals is because, if you are not pushing the results of your greater than function into a different array, then since the last sub-array is the animals array, it is always returning you the animal sub-array.

    var subarrays = [[1,2,3], ['a','b','c','d','e'], ['hippopatamus', 'zebra', 'crocodile','lion'], [false, 2]];

    You can use the forEach function of the array to iterate over the subarrays.

    var greaterArray = [];
    
    subarrays.forEach(function(subArray){
    
    if(subArray.length>3)
    {
    greaterArray.push(subArray);
    }
    });
    

    Or

    You can use the filter method also to achieve it more cleanly

    subArrays.filter(function(subArray)
    {
    return subArray.length>3;
    });
    

    The filter method accepts truthy or falsy value and based upon that, it creates a new array internally, and with the truthy values and returns the new array.