JavaScript —Searching through arrays

Convert your arrays to objects first to avoid too many iterations and speed up your code

Kristoffer Karlsson
Feb 5, 2017 · 2 min read

Say we have an array with objects where each object represents a data point in a chart. Each object has a ‘date’ field which is a string that represents the data point’s date, and a ‘value’ field which represents the value of some metric for that date.

var series = [
{date: '2017-01-01', value: 23000},
{date: '2017-01-02', value: 22000},
{date: '2017-01-03', value: 21000},
{date: '2017-01-04', value: 20000},
];

We also have an array of strings that represent dates that we want to plot in a chart.

var dates = ['2017–01–01', '2017–01–02'];

We are only interested in the objects in the ‘series’ array that have a ‘date’ field that exists in the ‘dates’ array.

The most common way would be to iterate through the dates array and the for every date iterate through the series array. This method is not so effective since we are doing unnecessarily many iterations.

for (var i = 0; i < dates.length; i++) {
for (var n = 0; n < series.length; n++) {
if(dates[i] === series[n].date){
console.log("Value " + series[n].value);
}
}
}

By converting our series array to a object we then only need to iterate through it one time, after that we can just fetch the values just like normal properties.

var seriesObj = {};
for (var i = 0; i < series.length; i++) {
var s = series[i];
seriesObj[s.date] = s.value;
}
for (var i = 0; i < dates.length; i++) {
console.log(" Value " + seriesObj[dates[i]]);
}

Found this useful? Don’t forget to follow me on twitter.

1CGu9Ctt1AuyXiWMJ2nEDoH1RRAKtStdjx

0xd2291b554075da7f61210db2648a7f0a2d006190

Kristoffer Karlsson

Written by

Software developer and indie game developer from Sweden. Been turning coffee into code since 2010.