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

后端 未结 9 1454
隐瞒了意图╮
隐瞒了意图╮ 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:26

    for a simple select you can use the reduce function of Array.
    Lets say you have an array of arrays of numbers:

    var arr = [[1,2],[3, 4]];
    arr.reduce(function(a, b){ return a.concat(b); });
    =>  [1,2,3,4]
    
    var arr = [{ name: "name1", phoneNumbers : [5551111, 5552222]},{ name: "name2",phoneNumbers : [5553333] }];
    arr.map(function(p){ return p.phoneNumbers; })
       .reduce(function(a, b){ return a.concat(b); })
    =>  [5551111, 5552222, 5553333]
    

    Edit:
    since es6 flatMap has been added to the Array prototype. SelectMany is synonym to flatMap.
    The method first maps each element using a mapping function, then flattens the result into a new array. Its simplified signature in TypeScript is:

    function flatMap(f: (value: A) => B[]): B[]
    

    In order to achieve the task we just need to flatMap each element to phoneNumbers

    arr.flatMap(a => a.phoneNumbers);
    

提交回复
热议问题