Main image
3rd April
2014
written by

As a developer in the .NET world where LINQ is first class citizen, when going to JavaScript it seems that some methods are missing. There is even a few libraries that tries to remedy this, but if you are just looking to get the job done the most often used methods are right at hand. (Looking for features such as Lazy-evaluation or observables, linq.js and RxJS offers these).

In the following I’ll list the most used operations and their JavaScript equivalents cheat sheet style. Notice that I’m using Lambda expressions in JavaScript to get the code a bit more concise, if they aren’t available just replace expressions like:

(data) => {}

with

function(data) {}

All operations are executed against this example:

var persons = [
    { firstname: 'Peter', lastname: 'Jensen', type: 'Person', age: 30 },
    { firstname: 'Anne', lastname: 'Jensen', type: 'Person', age: 50  },
    { firstname: 'Kurt', lastname: 'Hansen', type: 'Person', age: 40  }
];

Notice that some of the operations modifies the source array, if you don’t want that just clone it with:

persons.slice(0);

Every operation is named after the method’s name in LINQ:

All

C#
	var result = persons.All(person => person.type == "Person");
JavaScript
	var result = persons.filter(person => person.type == 'Person').length == persons.length;

Concat

C#
	var result = persons.Concat(persons);
JavaScript
	var result = persons.concat(persons);

Count

C#
	var result = persons.Count();
JavaScript
	var result = persons.length;

Distinct

C#
	var lastnames = persons.Select(person => person.lastname);
    var result = lastnames.Distinct();
	
JavaScript
	var lastnames = persons.map(person => person.lastname);
    var result = lastnames.filter((value, index) => lastnames.indexOf(value) == index);

Empty

C#
	var result = Enumerable.Empty<dynamic>();
JavaScript
	var result = [];

First

C#
	var result = persons.First();
JavaScript
	var result = persons[0];
    if (!result) throw new Error('Expected at least one element to take first')

FirstOrDefault

C#
	var result = persons.FirstOrDefault();
JavaScript
	var result = persons[0];

ForEach

C#
	var fullnames = new List<string>();
    persons.ForEach(person => fullnames.Add(person.firstname + " " + person.lastname));
JavaScript
var fullnames = [];
persons.forEach(person => fullnames.push(person.firstname + ' ' + person.lastname))

GroupBy

C#
	var result = persons.GroupBy(person => person.lastname);
JavaScript
	var result = persons.reduce((previous, person) => {
		(previous[person.lastname] = previous[person.lastname] || []).push(person);
    	return previous;
	}, []);

IndexOf

C#
	var result = persons.IndexOf(persons[2]);
JavaScript
	var result = persons.indexOf(persons[2]);

Last

C#
	var result = persons.Last();
JavaScript
	var result = persons[persons.length-1];
    if (!result) throw new Error('Expected at least one element to take last')

LastOrDefault

C#
	var result = persons.LastOrDefault();
JavaScript
	var result = persons[persons.length-1];

OrderBy

C#
	var result = persons.OrderBy(person => person.firstname);
JavaScript
	persons.sort((person1, person2) => person1.firstname.localeCompare(person2.firstname));

OrderByDescending

C#
	var result = persons.OrderByDescending(person => person.firstname);
JavaScript
	persons.sort((person1, person2) => person2.firstname.localeCompare(person1.firstname));

Reverse

C#
	persons.Reverse();
JavaScript
	var result = persons.reverse();

Select

C#
	var result = persons.Select(person => new {fullname = person.firstname + " " + person.lastname});
JavaScript
	var result = persons.map(person => ({ fullname: person.firstname + ' ' + person.lastname }) );

Single

C#
	var result = persons.Single(person => person.firstname == "Peter");
JavaScript
	var onePerson = persons.filter(person => person.firstname == "Peter"); 
    if (onePerson.length != 1) throw new Error('Expected at excactly one element to take single')
    var result = onePerson[0];

Skip

C#
	var result = persons.Skip(2);
JavaScript
	var result = persons.slice(2, persons.length); 

Take

C#
	var result = persons.Take(2);
JavaScript
	var result = persons.slice(0, 2);

Where

C#
	var result = persons.Where(person => person.lastname == "Jensen");
JavaScript
	var result = persons.filter(person => person.lastname == 'Jensen');

So clearly you don’t need a library if you only need the basic operations. The code above with tests is available at GitHub.

This post is also available in Danish at QED.dk.

8 Comments

  1. […] This post is also available in English at Complexitymaze.com. […]

  2. 03/04/2014

    You should use [].every instead of the unnecessary [].filter combined with [].length when doing the LINQ equivalent of .All()

    persons.every(person => person.type == ‘Person’)

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

  3. 04/04/2014

    @Kevin Reed, I did not know about every(). Thanks for the feedback

  4. 27/03/2015

    Did not know about Array.prototype.every as well. Cheers Kevin.

  5. 18/08/2015

    You can use JavaScriptLinq http://www.javascriptlinq.com/ It havs all linq functions

  6. Liazy
    10/02/2016

    persons.Any(p=>p.Type == “person”)
    persons.some(p=>p.type == “person”)

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

  7. Jorma
    02/06/2016

    Here is one missing function

    Select
    C#
    var result = persons.Select(person => new {fullname = person.firstname + ” ” + person.lastname});

    JavaScript
    var result = persons.Select(function(person) {return {fullname = person.firstname + ” ” + person.lastname});

  8. 06/01/2020

    Check out an implementation of LINQ in Javascript using modern ES6 language features: https://siderite.dev/blog/linq-in-javascript-linqer/

Leave a Reply

WordPress Appliance - Powered by TurnKey Linux