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:
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
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.
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.
Source: Stackoverflow.com