I am trying to rewrite a function in ES6 to use filtering over an array of objects. Currently the code loops through the array and copies array members that meet a criteria to a new array which it then returns. The criteria is based upon the previous value in the array. I want to filter out all array items where the timestamp field of the object is < 4 minutes.
let final = [];
final.push(data[0]);
for (let i = 1, j = data.length; i < j; i++) {
// if time difference is > 4 minutes add to our final array
if (data[i].timestamp - data[i-1].timestamp > 240) {
final.push(data[i]);
}
}
return final;
There has got to be a better way of doing this. I thought of using an arrow function, but I dont see how I would access the timestamp of the previous array item object when iterating.
I am trying to rewrite a function in ES6 to use filtering over an array of objects. Currently the code loops through the array and copies array members that meet a criteria to a new array which it then returns. The criteria is based upon the previous value in the array. I want to filter out all array items where the timestamp field of the object is < 4 minutes.
let final = [];
final.push(data[0]);
for (let i = 1, j = data.length; i < j; i++) {
// if time difference is > 4 minutes add to our final array
if (data[i].timestamp - data[i-1].timestamp > 240) {
final.push(data[i]);
}
}
return final;
There has got to be a better way of doing this. I thought of using an arrow function, but I dont see how I would access the timestamp of the previous array item object when iterating.
Share Improve this question asked Oct 11, 2018 at 16:41 GregGreg 1,8533 gold badges19 silver badges26 bronze badges 1- Two answers with the same solution. Thanks to both of you! – Greg Commented Oct 11, 2018 at 16:52
2 Answers
Reset to default 7The Array.filter()
method passes the index (i
) to the callback function, and you can use it to get the previous value from the array. To take the 1st item as well, I use the condition !i
, which is evaluated to true
when i
is 0.
const data = [{ timestamp: 1 }, { timestamp: 3 }, { timestamp: 250 }, { timestamp: 1000 }];
const final = data.filter((o, i) =>
!i || (o.timestamp - data[i-1].timestamp > 240)
);
console.log(final);
let prevTs = -Infinity;
const result = data.filter((d) => {
const localResult = (d.timestamp - prevTs) > 240;
prevTs = d.timestamp;
return localResult;
});
Or you can use index arg in your filter callback:
data.filter((d, i) => {
if (!i) {
return true;
}
return (d.timestamp - data[i - 1].timestamp) > 240
});