JSFiddle - React, Tailwind, and code Playground
Speed comparison of solutions in
http://stackoverflow.com/questions/8101113/localstorage-get-specific-localstorage-value-of-which-contains-many-items
HTML
<div id="out"></div>
CSS
strong { font-weight: bold; }
td { text-align: right; padding: .1em 1em }
tr:nth-child(odd) { background: #eef; }
p, table { margin: 1em }
JavaScript
var testItem,
data = [{"id":"item-1","href":"google.com","icon":"google.com"},
{"id":"item-2","href":"youtube.com","icon":"youtube.com"},
{"id":"item-3","href":"google.com","icon":"google.com"},
{"id":"item-4","href":"google.com","icon":"google.com"},
{"id":"item-5","href":"youtube.com","icon":"youtube.com"},
{"id":"item-6","href":"asos.com","icon":"asos.com"},
{"id":"item-7","href":"google.com","icon":"google.com"},
{"id":"item-8","href":"mcdonalds.com","icon":"mcdonalds.com"}];
function getItemById_array_filter(data, id) {
// filter array down to only the item that has the id
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
var ret = data.filter( function (item) {
return item.id === id;
});
// Return the first item from the filtered array
// returns undefined if item was not found
return ret[0];
}
function getItemById_custom_loop(data, id) {
var i, len;
for (i = 0, len = data.length; i < len; i += 1) {
if(id === data[i].id) {
return data[i];
}
}
return null;
}
function getItemById_jquery_filter(data, id) {
return $(data).filter(function(){return this.id == "item-3";})[0];
}
function test(fn, rounds) {
var testItem,
st,
sp;
st = (new Date()).getTime();
for(; rounds > 0; rounds -= 1) {
testItem = fn(data, 'item-8');
}
sp = (new Date()).getTime()
return sp - st;
}
$('#out').html('<p>Running tests...</p>');
var rounds = 50000,
native = test(getItemById_array_filter, rounds),
custom = test(getItemById_custom_loop, rounds),
jq = test(getItemById_jquery_filter, rounds);
$('#out').html('<p>Speed comparison of finding an object by id in an array, after ' + rounds + ' rounds.</p>' +
'<table>' +
'<tr><td>Native Array.filter </td><td>' + native + ' milliseconds</td></tr>' +
'<tr><td>Custom loop </td><td>' + custom + ' milliseconds</td></tr>' +
'<tr><td>jQuery filter </td><td>' + jq + '...