I have an array like this:
I want to find the location of the movie that's released in 1999.
Should return 1
.
What's the easiest way?
Thanks.
I have an array like this:
I want to find the location of the movie that's released in 1999.
Should return 1
.
What's the easiest way?
Thanks.
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
Built in? Use loops.
You want to get fancy? Linq to Javascript: http://jslinq.codeplex.com/
Something like:
function findMovieIndices(movies, prop, value) { var result = []; for(var i = movies.length; i--; ) { if(movies[i][prop] === value) { result.push(i); // personally I would return the movie objects } } return result; }
Usage:
var indices = findMovieIndices(movies, "ReleaseYear", "1999");
Maybe this gives you some idea for a more generalized function (if you need it).
Since you've also tagged it with jQuery, you could use the 'map' function:
var movies = $.map(movies,function(item,index){ return item.ReleaseYear == 1999 ? index : null; });
This will return an array of indexes for all movies with the year of 1999. If you wanted the movies themselves as an array:
var movies = $.map(movies,function(item){ return item.ReleaseYear == 1999 ? item : null; });
If functional style programming is applicable:
_.indexOf(_.pluck(movies, "ReleaseYear"), "1999")
Because it's that simple. The functional toolkit that is underscore.js
can be very powerful.
You'll have to create your own searching function.
Of course, this way of doing it actually affects every array you create.. which is maybe not what you want.. you can create your own array object then ...