5

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.

0

6 Answers 6

7

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

Sign up to request clarification or add additional context in comments.

7 Comments

if you only need to get one movie then add a break; at the end, before closing the if. PS: Great avatar!
One quick note. You will want to break out of that loop once the condition is satisfied. Could do a "return i;"
Yes, or return i; if it is a function. (in addition to my previous comment)
Thanks @JCOC611 and @Aliester. I'm assuming OP wants to process each entry having the year 1999, otherwise adding a break is a good optimization. The avatar is from a facebook app, can't remember which :)
This approach will work if you only need the first occurrence of a movie in 1999. You'd want to do it differently if there could be more than one movie that has 1999 for ReleaseYear.
|
2

Built in? Use loops.

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

Comments

2

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).

1 Comment

+1, but diff usecases. for example jquery $.inArray returns the key too.
2

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; 
});

3 Comments

@Raynos - This is using the jQuery map function. If anything other than null or undefined is returned then it will insert that into the resulting array.
my original comment was wrong but the solution doesn't really handle a not found case apart from returning an empty array.
@Raynos An empty set is my way of handling not found :)
1

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.

_.indexOf , ._pluck

Comments

0

You'll have to create your own searching function.

Array.prototype.findMovieByYear = function (findYear) {

    for (var i = 0; i < this.length; i++) {
        // this actually returns the element, maybe you just want
        // to return the array index ( the i param )
        if (this[i].Release == findYear) return this[i];
    }

    return null;
    // or return -1 or whatever if you want to return the index

};

// now you can call:
movies.findMovieByYear('1998');
// and that should return
{ Name: "The Red Violin", ReleaseYear: "1998", Director: "François Girard" }

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 ...

4 Comments

Don't extend native prototypes. We all know it's a bad idea because it ruins for in loops and breaks various 3rd party libraries. At least put a disclaimer on it.
@Raynos: Well, you should not use for...in for arrays anyway ;) But yes, I remember a problem with jQuery and extended Object or Array prototype...
@FelixKling it's not me that i'm worried about as much as fellow programmers and other 3rd party libraries / plugins.
Thanks guys, small mistake :) but I already mentioned that you should create your own object, instead of extending the array prototype.. for simplicity's sake I just wanted to keep the code simple (and I don't like typing code into the SO textbox)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.