Filter array
by logankd
JavaScript
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('initial array to filter');
console.log(JSON.stringify(processingProgressTimeoutIds));
var keyName = 'test';
var match = processingProgressTimeoutIds.filter(function (item) {
return item.name === keyName;
})[0];
console.log('Result from filter:');
console.log(JSON.stringify(match));
// optimization
var match2 = processingProgressTimeoutIds.some(function (element, index, array) {
return element.name === keyName;
});
console.log('Result from some:');
console.log(JSON.stringify(match2));
// if you have the full object
var match3 = processingProgressTimeoutIds.indexOf(file);
console.log('Result from indexOf:');
console.log(JSON.stringify(match3));
// http://jsperf.com/array-find-equal
// indexOf is faster, but I need to find it by the key
//ES6 will rock though, array comprehension FTW
// var ys = [x of xs if x == 3];
// var y = ys[0];
var indexMatch = -1;
for (var i = 0; i < processingProgressTimeoutIds.length; i++) {
if (processingProgressTimeoutIds[i].name ===keyName) {
indexMatch = i;
break;
}
}
// match
var match4 = processingProgressTimeoutIds[indexMatch];
// if you need to replace it
var replacementFile = { name: 'test4', timeId: 4 }
processingProgressTimeoutIds[indexMatch] = replacementFile;
console.log('Result from index matching:');
console.log(JSON.stringify(match4));
console.log(JSON.stringify(processingProgressTimeoutIds[indexMatch]));