-4

I have an array of students (all IDs are unique):

[Object {ID: 1, "John"}, Object  {ID: 2, "Joseph"} ]

I have another array of strings ["John","Ram"] (let's call this "Array 2"). How can I find the IDs of students whose names are there in Array 2 (without considering case, i.e. case insensitive)?

Kuttan Sujith
  • 7,889
  • 18
  • 64
  • 95

1 Answers1

1

Edit: Remove jQuery and fix case-sensitivity problem. Note, this is no longer compatible with IE8 due to the use of map(), forEach() and indexOf() on Array.prototype.

Something along these lines would do the trick:

var names = ['John', 'Joe', 'Ralph'],
    data = [
        {
            id: 1,
            name: 'John'
        },
        {
            id: 2,
            name: 'Joseph'
        },
        {
            id: 3,
            name: 'ralph'
        }
    ],
    results = [];

var lnames = names.map(function(name) {
    return name.toLowerCase();
});

data.forEach(function(item) {
    if (lnames.indexOf(item.name.toLowerCase()) > -1) {
        results.push(item.id);
    }
});

console.log('found: ', results);

Here's a live example: http://jsfiddle.net/6ptz3/2/

tiffon
  • 5,040
  • 25
  • 34
  • Here is a native JS solution btw - which _still_ doesn't answer OP's question because the question isn't well formed and the structure isn't clear: `var ids = studentsArray.filter(function(elem){ return namesArray.indexOf(elem.name) !== -1; /* in the names array*/ }).map(function(elem){ return elem.ID; });` – Benjamin Gruenbaum Oct 28 '13 at 12:29
  • Prior to the edit the last sentence in the question read: "[I am using jquery]"... So, to answer your question: the OP. – tiffon Oct 28 '13 at 12:31
  • Apologies then, my bad. I did not see OP mentioned he was using jQuery before the edit. – Benjamin Gruenbaum Oct 28 '13 at 12:36
  • No problem, thanks for pointing out jQuery was removed from the question. Also, I had to fix a case-sensitivity problem which I think may also be present in the solution you mention in your comment. – tiffon Oct 28 '13 at 12:59