MarqueIV MarqueIV - 5 months ago 10
Javascript Question

Does JavaScript have a similar capability as LINQ's Select statement?

Say I have an array of window objects and each has an ID property and I need to get an array of those IDs.

In LINQ, I would just do this...

var ids = windows.Select(window => window.id).ToArray();


Nice and simple. But in Javascript, I've been doing this...

var ids = [];

for(i = 0; i < windows.length; i++)
{
var window = windows[i];
ids.push(window.id);
}


I'm just wondering if there's a simpler/easier way in Javascript, similar to LINQ's elegant solution.

Answer

If you are happy with IE8 and above support, array.map() is a comparable option:

var ids = windows.map(function(val) {
    return val.id;
});

This of course becomes even more succinct (and similar to LINQ) if using ES6 fat arrow functions, although this will require a transpiler if supporting non-cutting edge browsers:

var ids = windows.map(x => x.id);