I have an array of objects that look similar to this
[ { lastseen: 1640694661000, value: "test1"}, { lastseen: 1640696227000, value: "test2"}]
New object that I am trying to insert is
{ lastseen: 1640695661564, value: "test1"}
I need to push this into a new array based on its recent last seen when the values are same . Only unique values should be present in the final array and that has recent lastseen
The output should look like
newArr = [ { lastseen: 1640695661564, value: "test1"}, { lastseen: 1640696227000, value: "test2"} ]
In this case test1 with lastseen 1640695661564 is recent and only one such object is present in the final array
Code that I tried
function uniqueAndInsert(currArr, input){
const idx = currArr.findIndex((obj) => {
obj.lastseen < input.lastseen;
});
if(idx!==-1){
currArr.splice(idx, 0, input);
}
else{
currArr.splice(0);
currArr.push(input);
}
return currArr;
}
CodePudding user response:
Try this one
function replaceArrayItemByValue(array = [], item) {
const hasNewItem = array.some(e => e.value === item.value)
if (!hasNewItem) return [...array, item]
return array.map(arrayItem => {
const isItemToReplace = arrayItem.value === item.value
if (isItemToReplace) return item
return arrayItem
})
}
console.log(
replaceArrayItemByValue(
[
{ value: '1', time: 1 },
{ value: '2', time: 2 }
],
{
value: '1',
time: 'new time'
}
)
)
console.log(
replaceArrayItemByValue(
[
{ value: '1', time: 1 },
{ value: '2', time: 2 }
],
{
value: '3',
time: 'new time'
}
)
)
CodePudding user response:
There are 3 cases to handle. 1) input
is recent than current data (update data) 2) input
is not recent than current data (no change) 3) input
does not exist in current data (add data).
function uniqueAndInsert(currArr, input) {
const item = currArr.find(({ value }) => value === input.value);
if (item && item.lastseen >= input.lastseen) {
// data is up to date, no changes just return original array
return currArr;
}
// filter the same value data if exist and add input
return currArr.filter(({ value }) => value !== input.value).concat(input);
}
// alternatively, to do it one iteration
function uniqueAndInsert2(currArr, input) {
const output = [];
let exist = false;
currArr.forEach(({ value, lastseen }) => {
if (value === input.value) {
output.push({ value, lastseen: Math.max(input.lastseen, lastseen) });
exist = true;
} else {
output.push({ value, lastseen });
}
});
if (!exist) {
output.push(input);
}
return output;
}