В случае, если вы решите сохранить структуру массива объектов, вы можете реализовать метод, используя Array.findIndex () и Array.splice () следующим образом:
const pushWithCheck = (arr, obj) =>
{
let idx = arr.findIndex(({key}) => key === obj.key);
if (idx >= 0)
arr.splice(idx, 1, obj);
else
arr.push(obj);
}
var _status = [];
pushWithCheck(_status, {key: 'BOB', value: 10});
pushWithCheck(_status, {key: 'TOM', value: 3});
pushWithCheck(_status, {key: 'ROB', value: 22});
pushWithCheck(_status, {key: 'JON', value: 7});
console.log("Before duplicated key:", _status);
pushWithCheck(_status, {key: 'BOB', value: 20});
pushWithCheck(_status, {key: 'ROB', value: 99});
console.log("After duplicated key:", _status);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Теперь, чтобы отсортировать по свойству key
объектов и получить последние 2
элементы, вы можете использовать Array.sort () и Array.slice () с отрицательным (-2
) аргументом, например:
const pushWithCheck = (arr, obj) =>
{
let idx = arr.findIndex(({key}) => key === obj.key);
if (idx >= 0)
arr.splice(idx, 1, obj);
else
arr.push(obj);
}
// Generate the _status array.
var _status = [];
pushWithCheck(_status, {key: 'BOB', value: 10});
pushWithCheck(_status, {key: 'TOM', value: 3});
pushWithCheck(_status, {key: 'ROB', value: 22});
pushWithCheck(_status, {key: 'JON', value: 7});
pushWithCheck(_status, {key: 'BOB', value: 20});
pushWithCheck(_status, {key: 'ROB', value: 99});
console.log("_status is: ", _status);
// Sort the _status array by ascending.
let sorted = _status.slice().sort((a, b) => a.key.localeCompare(b.key));
// Get last two elements of the sorted array.
let lastTwo = sorted.slice(-2);
console.log("Sorted is: ", sorted);
console.log("Last two elements are: ", lastTwo);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}