Run
Run

Reputation: 57196

Javascript - better ways of searching and matching data in an object array?

Is there a better way of doing the thing below? I want to look up the data in the particles array that match the search-date's index/ position in the timestamp array.

My sample data:

var data = {
    particles: ['1.0',
    '1.1',
    '1.2',
    '2.0',
    '2.1',
    '2.2',
    '3.0',
    '3.1'],

    timestamp: ['2016-10-10',
    '2016-10-10',
    '2016-10-10',
    '2016-10-11',
    '2016-10-11',
    '2016-10-11',
    '2016-10-13',
    '2016-10-13'],
};

My code:

var find = '2016-10-11';
var lookup = {};

var timestamp = [];
var index = [];
for (var key in data.timestamp) {
    if (data.timestamp[key] === find) {
        timestamp.push(data.timestamp[key]);
        index.push(key);
    }
}
console.log(timestamp);
// --> ["2016-10-11", "2016-10-11", "2016-10-11"]

var particles = [];
for (var key in data.particles) {
    // Check if the key is in the index.
    if (index.indexOf(key) > -1) {
        particles.push(data.particles[key]);
    }
}
console.log(particles);
// --> ["2.0", "2.1", "2.2"]

lookup.particles = particles;
lookup.timestamp = timestamp;

console.log(lookup);

Result:

{
    particles: [
    '2.0',
    '2.1',
    '2.2'
    ],

    timestamp: [
    '2016-10-11',
    '2016-10-11',
    '2016-10-11'],
}

I will have thousands of items in timestamp and particles so I think the looping above may cause some performance issue in the future.

Also, I might have more keys in the object in the futures:

{
   particles1: [...],
   particles2: [...],
   particles3: [...],
   timestamp: [...]
}

So my manually looking the matching data probably not a good way to go for.

Any better ideas?

timestamp is always a fixed key in the data.

I prefer vanilla Javascript solutions.

Upvotes: 1

Views: 60

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

You could get the indices first and then the result set for every property

var data = { particles: ['1.0', '1.1', '1.2', '2.0', '2.1', '2.2', '3.0', '3.1'], timestamp: ['2016-10-10', '2016-10-10', '2016-10-10', '2016-10-11', '2016-10-11', '2016-10-11', '2016-10-13', '2016-10-13'] },
    find = '2016-10-11',
    lookup = {},
    indices = [];


data.timestamp.forEach(function (a, i) {
    a === find && indices.push(i);
});

Object.keys(data).forEach(function (k) {
    lookup[k] = indices.map(function (i) {
        return data[k][i];
    });
});
 
console.log(lookup);

Upvotes: 3

Related Questions