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

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

    Here you go, a rewritten version of joel-harkes' answer in TypeScript as an extension, usable on any array. So you can literally use it like somearray.selectMany(c=>c.someprop). Trans-piled, this is javascript.

    declare global {
        interface Array {
            selectMany(selectListFn: (t: TIn) => TOut[]): TOut[];
        }
    }
    
    Array.prototype.selectMany = function ( selectListFn: (t: TIn) => TOut[]): TOut[] {
        return this.reduce((out, inx) => {
            out.push(...selectListFn(inx));
            return out;
        }, new Array());
    }
    
    
    export { };
    

提交回复
热议问题