How to do equivalent of LINQ SelectMany() just in javascript

后端 未结 9 1458
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 16:54

Unfortunately, I don\'t have JQuery or Underscore, just pure javascript (IE9 compatible).

I\'m wanting the equivalent of SelectMany() from LINQ functionality.

<
9条回答
  •  一向
    一向 (楼主)
    2020-12-13 17:20

    I would do this (avoiding .concat()):

    function SelectMany(array) {
        var flatten = function(arr, e) {
            if (e && e.length)
                return e.reduce(flatten, arr);
            else 
                arr.push(e);
            return arr;
        };
    
        return array.reduce(flatten, []);
    }
    
    var nestedArray = [1,2,[3,4,[5,6,7],8],9,10];
    console.log(SelectMany(nestedArray)) //[1,2,3,4,5,6,7,8,9,10]
    

    If you don't want to use .reduce():

    function SelectMany(array, arr = []) {
        for (let item of array) {
            if (item && item.length)
                arr = SelectMany(item, arr);
            else
                arr.push(item);
        }
        return arr;
    }
    

    If you want to use .forEach():

    function SelectMany(array, arr = []) {
        array.forEach(e => {
            if (e && e.length)
                arr = SelectMany(e, arr);
            else
                arr.push(e);
        });
    
        return arr;
    }
    

提交回复
热议问题