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

后端 未结 9 1393
隐瞒了意图╮
隐瞒了意图╮ 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<A, B>(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);
    
    0 讨论(0)
  • 2020-12-13 17:34

    You can try the manipula package that implements all C# LINQ methods and preserves its syntax:

    Manipula.from(petOwners).selectMany(x=>x.Pets).toArray()
    

    https://github.com/litichevskiydv/manipula

    https://www.npmjs.com/package/manipula

    0 讨论(0)
  • 2020-12-13 17:36

    Sagi is correct in using the concat method to flatten an array. But to get something similar to this example, you would also need a map for the select part https://msdn.microsoft.com/library/bb534336(v=vs.100).aspx

    /* arr is something like this from the example PetOwner[] petOwners = 
                        { new PetOwner { Name="Higa, Sidney", 
                              Pets = new List<string>{ "Scruffy", "Sam" } },
                          new PetOwner { Name="Ashkenazi, Ronen", 
                              Pets = new List<string>{ "Walker", "Sugar" } },
                          new PetOwner { Name="Price, Vernette", 
                              Pets = new List<string>{ "Scratches", "Diesel" } } }; */
    
    function property(key){return function(x){return x[key];}}
    function flatten(a,b){return a.concat(b);}
    
    arr.map(property("pets")).reduce(flatten,[])
    
    0 讨论(0)
提交回复
热议问题