Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript find in array

I have an array like this:

  var movies = [
  { Name: "The Red Violin", ReleaseYear: "1998", Director: "François Girard" },
  { Name: "Eyes Wide Shut", ReleaseYear: "1999", Director: "Stanley Kubrick" },
  { Name: "The Inheritance", ReleaseYear: "1976", Director: "Mauro Bolognini" }
  ];

I want to find the location of the movie that's released in 1999.

Should return 1.

What's the easiest way?

Thanks.

like image 809
Mark Avatar asked Dec 12 '22 16:12

Mark


2 Answers

You will have to iterate through each value and check.

for(var i = 0; i < movies.length; i++) {
    if (movies[i].ReleaseYear === "1999") {
        // i is the index
    }
}

Since JavaScript has recently added support for most common collection operations and this is clearly a filter operation on a collection, instead you could also do:

var moviesReleasedIn1999 = movies.filter(function(movie) {
    return movie.ReleaseYear == "1999";
});

assuming you're not interested in the indexes but the actual data objects. Most people aren't anyways :)

.filter is not supported in all browsers, but you can add it yourself to your code base: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter#Compatibility

like image 81
Anurag Avatar answered Dec 31 '22 03:12

Anurag


Built in? Use loops.

You want to get fancy? Linq to Javascript: http://jslinq.codeplex.com/

like image 27
Sean Avatar answered Dec 31 '22 04:12

Sean