我有如下数组,我想按键对它进行排序,然后删除除最后2个项目以外的所有内容,并删除其余的内容。
var status = new Array();
status.push({key: 'BOB', value: 10});
status.push({key: 'TOM', value: 3});
status.push({key: 'ROB', value: 22});
status.push({key: 'JON', value: 7});
例如,如果我再次用重复的键推到下面:
status.push({key: 'BOB', value: 20});
我需要以下输出,如何在javascript中实现这一目标。
[
{
"key": "BOB",
"value": 20
},
{
"key": "TOM",
"value": 3
},
{
"key": "ROB",
"value": 22
},
{
"key": "JON",
"value": 7
}
]
注意:我稍后需要按键对它进行排序。
编辑:如果我有这样的对象,如何按键排序?并仅获取最后2项,并删除其余项。
var status = new Object();
status['BOB'] = 10
status['TOM'] = 3
status['ROB'] = 22
status['JON'] = 7
答案 0 :(得分:1)
答案 1 :(得分:0)
使用对象代替使用数组:
(function () {
var status = {};
status['BOB'] = 10;
status['TOM'] = 3;
status['ROB'] = 22;
status['JON'] = 7;
status['BOB'] = 20;
// convert to array
var output = Object.keys(status)
// sort by key
.sort()
// keep last two after sorting
.slice(-2)
// convert [key, value] to { key, value }
.map(function (key) {
return { key: key, value: status[key] };
});
console.log(output);
})();
.as-console-wrapper{max-height:100%!important}
答案 2 :(得分:0)
如果您要按照其他人建议的方式进行操作,则应使用set集,其中总是包含唯一的元素
// initialize the map
var stats = new Set([['BOB',10],['TOM',3],['ROB',22],['JON',7]]);
// set a specific key's value
stats.add('BOB', 20);
// sort by key
var keys = Array.from(stats.keys());
keys.sort();
// get the last two
keys = keys.slice(-2);
// map the remaining keys to the desired structure
var result = keys
console.log(result);
我认为这可以回答您所有的问题
let status1 = [];
status1.push({
key: 'BOB',
value: 10
}, {
key: 'TOM',
value: 3
}, {
key: 'ROB',
value: 22
}, {
key: 'JON',
value: 7
});
console.log('Initial array', status1);
//const newItem = {
// key: 'BOB',
// value: 20
//};
const newItem = {
key: 'BOB',
value: 99
};
for (let i = 0; i < status1.length; i++) {
if (status1[i].key === newItem.key) {
status1[i] = newItem;
}
}
Array.prototype.inArray = function(comparer) {
for(var i=0; i < this.length; i++) {
if(comparer(this[i])) return true;
}
return false;
};
Array.prototype.pushIfNotExist = function(element, comparer) {
if (!this.inArray(comparer)) {
this.push(element);
}
};
//https://stackoverflow.com/questions/1988349/array-push-if-does-not-exist
status1.pushIfNotExist(newItem, function(e) {
return e.key === newItem.key;
});
console.log('after push', status1);
function sortByKey(array, key) {
return array.sort(function (a, b) {
var x = a[key];
var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
sortByKey(status1, 'key');
console.log('AFter sort', status1);
console.log('Last item', status1[status1.length - 1]);
console.log('Second Last item', status1[status1.length - 2]);
答案 3 :(得分:0)
如果您决定保留对象数组的结构,则可以通过以下方式使用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()与否定({{1} })参数,例如:
-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);