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

后端 未结 9 1477
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 17:18

    // you can save this function in a common js file of your project
    function selectMany(f){ 
        return function (acc,b) {
            return acc.concat(f(b))
        }
    }
    
    var ex1 = [{items:[1,2]},{items:[4,"asda"]}];
    var ex2 = [[1,2,3],[4,5]]
    var ex3 = []
    var ex4 = [{nodes:["1","v"]}]
    

    Let's start

    ex1.reduce(selectMany(x=>x.items),[])
    

    => [1, 2, 4, "asda"]

    ex2.reduce(selectMany(x=>x),[])
    

    => [1, 2, 3, 4, 5]

    ex3.reduce(selectMany(x=> "this will not be called" ),[])
    

    => []

    ex4.reduce(selectMany(x=> x.nodes ),[])
    

    => ["1", "v"]

    NOTE: use valid array (non null) as intitial value in the reduce function

提交回复
热议问题