Find an element in a JavaScript array

Posted by Aligned on Geeks with Blogs See other posts from Geeks with Blogs or by Aligned
Published on Fri, 22 Aug 2014 06:27:46 GMT Indexed on 2014/08/22 22:21 UTC
Read the original article Hit count: 331

Filed under:

Originally posted on: http://geekswithblogs.net/Aligned/archive/2014/08/22/find-an-element-in-a-javascript-array.aspx

I needed a C# Dictionary like data structure in JavaScript and then a way to find that object by a key. I had forgotten how to do this, so did some searching and talked to a colleague and came up with this JsFiddle.

See the code in my jsFiddle or below:

var processingProgressTimeoutIds = [];
var file = {
    name: 'test',
    timeId: 1
};
var file2 = {
    name: 'test2',
    timeId: 2
};
var file3 = {
    name: 'test3',
    timeId: 3
};

processingProgressTimeoutIds.push({
    name: file.name,
    timerId: file.id
});
processingProgressTimeoutIds.push({
    name: file2.name,
    timerId: file2.id
});
processingProgressTimeoutIds.push({
    name: file3.name,
    timerId: file3.id
});

console.log(JSON.stringify(processingProgressTimeoutIds));

var keyName = 'test';
var match = processingProgressTimeoutIds.filter(function (item) {
    return item.name === keyName;
})[0];
console.log(JSON.stringify(match));

// optimization
var match2 = processingProgressTimeoutIds.some(function (element, index, array) {
    return element.name === keyName;
});
console.log(JSON.stringify(match2));

// if you have the full object
var match3 = processingProgressTimeoutIds.indexOf(file);
console.log(JSON.stringify(match3));

// http://jsperf.com/array-find-equal – from Dave
// indexOf is faster, but I need to find it by the key, so I can’t use it here
//ES6 will rock though, array comprehension! – also from Dave
//  var ys = [x of xs if x == 3];
//  var y = ys[0];
Here’s a good blog post on Array comprehension.

© Geeks with Blogs or respective owner

Related posts about JavaScript