Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Easy JavaScript Generic List Implementation

4.86/5 (5 votes)
5 May 2012CPOL 22K   129  
A quick and easy JavaScript implementation of a Generic List with LINQ support.

Introduction

Generic collections in .NET, in combination with LINQ, are powerful tools for the C# or VB.NET developer; however, nothing like it comes with JavaScript. This code provides the beginnings of a JavaScript implementation for a Generic List. Fortunately, due to JavaScript's flexibility, this can be achieved with a relatively small amount of code. 

Using the code 

The following public functions with a description of each are currently supported:

  • Add: Add an element to the end of the list.
  • ElementAt: Get the element at a specific index in the list.
  • Where: Return a copy of this List object with only the elements that meet the criteria.
  • FirstOrDefault: Return the first object in the list that meets the 'query' criteria or null if
  • Count: Return the number of elements in the list. 
  • OrderBy: Order (ascending) the objects in the list by the given object property name.
  • OrderByDescending: Order (descending) the objects in the list by the given object property
  • Data: Set the list data using the passed in array. 

Example of using Car objects to fill the List:

JavaScript
function Car(make, model)
{
    this.make = make;
    this.model = model;
}

var myList = new List();
myList.Add(new Car("Honda", "CR-V"));
myList.Add(new Car("Nissan", "Sentra"));
myList.Add(new Car("Honda", "Civic"));

var selList = myList.Where("make == 'Honda'").OrderByDescending("model");

History

Version 1 uploaded on May 4, 2012.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)