[javascript] Javascript Equivalent to C# LINQ Select

Following this question here :

Using the checked binding in knockout with a list of checkboxes checks all the checkboxes

I've created some checkboxes using knockout that allow selection from an array. working fiddle taken from above post:

http://jsfiddle.net/NsCXJ/

Is there a simple way of creating an array of just the fruit's ID's?

I'm more at home with C# where I would do something along the lines of selectedFruits.select(fruit=>fruit.id);

Is there some method/ready made function for doing something similar with javascript/jquery? Or would the simplest option be to loop through the list and create a second array? I intend to post the array back to the server in JSON so am trying to minimize the data sent.

This question is related to javascript jquery knockout.js

The answer is


Since you're using knockout, you should consider using the knockout utility function arrayMap() and it's other array utility functions.

Here's a listing of array utility functions and their equivalent LINQ methods:

arrayFilter() -> Where()
arrayFirst() -> First()
arrayForEach() -> (no direct equivalent)
arrayGetDistictValues() -> Distinct()
arrayIndexOf() -> IndexOf()
arrayMap() -> Select()
arrayPushAll() -> (no direct equivalent)
arrayRemoveItem() -> (no direct equivalent)
compareArrays() -> (no direct equivalent)

So what you could do in your example is this:

var mapped = ko.utils.arrayMap(selectedFruits, function (fruit) {
    return fruit.id;
});

If you want a LINQ like interface in javascript, you could use a library such as linq.js which offers a nice interface to many of the LINQ methods.

var mapped = Enumerable.From(selectedFruits)
    .Select("$.id") // 1 of 3 different ways to specify a selector function
    .ToArray();

I am answering the title of the question rather than the original question which was more specific.

With the new features of Javascript like iterators and generator functions and objects, something like LINQ for Javascript becomes possible. Note that linq.js, for example, uses a completely different approach, using regular expressions, probably to overcome the lack of support in the language at the time.

With that being said, I've written a LINQ library for Javascript and you can find it at https://github.com/Siderite/LInQer. Comments and discussion at https://siderite.dev/blog/linq-in-javascript-linqer.

From previous answers, only Manipula seems to be what one would expect from a LINQ port in Javascript.


Take a look at fluent, it supports almost everything LINQ does and based on iterables - so it works with maps, generator functions, arrays, everything iterable.


The most similar C# Select analogue would be a map function. Just use:

var ids = selectedFruits.map(fruit => fruit.id);

to select all ids from selectedFruits array.

It doesn't require any external dependencies, just pure JavaScript. You can find map documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map


Had to merge this nice answers. It revealed something like that;

Extension;

 Array.prototype.where = function (filter) {

                                var collection = this;

                                switch (typeof filter) {

                                    case 'function':
                                        return $.grep(collection, filter);

                                    case 'object':
                                        for (var property in filter) {
                                            if (!filter.hasOwnProperty(property))
                                                continue; // ignore inherited properties

                                            collection = $.grep(collection, function (item) {
                                                return item[property] === filter[property];
                                            });
                                        }
                                        return collection.slice(0); // copy the array 
                                    // (in case of empty object filter)

                                    default:
                                        throw new TypeError('func must be either a' +
                                            'function or an object of properties and values to filter by');
                                }
                            };

Usage;



masterTableView.get_dataItems().where(function (t) {
if (t.findElement("_invoiceGridCheckbox").checked) {
    invoiceIds.push(t.getDataKeyValue("Id"));
  }
});

You can try manipula package, which implement all of C# LINQ methods and save its syntax: https://github.com/litichevskiydv/manipula

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

Your example selectedFruits.select(fruit=>fruit.id); will be implemented with manipula as

Manipula.from(selectedFruits).select(fruit=>fruit.id);

I know it is a late answer but it was useful to me! Just to complete, using the $.grep function you can emulate the linq where().

Linq:

var maleNames = people
.Where(p => p.Sex == "M")
.Select(p => p.Name)

Javascript:

// replace where  with $.grep
//         select with $.map
var maleNames = $.grep(people, function (p) { return p.Sex == 'M'; })
            .map(function (p) { return p.Name; });

The ES6 way:

let people = [{firstName:'Alice',lastName:'Cooper'},{firstName:'Bob',age:'Dylan'}];
let names = Array.from(people, p => p.firstName);
for (let name of names) {
  console.log(name);
}

also at: https://jsfiddle.net/52dpucey/


Dinqyjs has a linq-like syntax and provides polyfills for functions like map and indexOf, and has been designed specifically for working with arrays in Javascript.


You can also try linq.js

In linq.js your

selectedFruits.select(fruit=>fruit.id);

will be

Enumerable.From(selectedFruits).Select(function (fruit) { return fruit.id;  });

Take a peek at underscore.js which provides many linq like functions. In the example you give you would use the map function.


I have build a Linq library for TypeScript under TsLinq.codeplex.com that you can use for plain javascript too. That library is 2-3 times faster than Linq.js and contains unit tests for all Linq methods. Maybe you could review that one.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to knockout.js

json parsing error syntax error unexpected end of input Javascript Equivalent to C# LINQ Select KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.." twitter bootstrap autocomplete dropdown / combobox with Knockoutjs Change event on select with knockout binding, how can I know if it is a real change? How to clear/remove observable bindings in Knockout.js? Passing parameter using onclick or a click binding with KnockoutJS Knockout validation How to force a view refresh without having it trigger automatically from an observable?