2 回答

TA貢獻(xiàn)1831條經(jīng)驗 獲得超9個贊
好吧,它并不是那么優(yōu)雅,但你可以像下面那樣做。
var input = [{"mickey gray": 5}, {"mickey gray": 50}, {"mickey gray" : 500}, {"steve smith": 5}, {"steve smith": 50}, {"steve smith": 500}];
// basically - groupby key
var intermediate = input.reduce( (acc,i) => {
Object.keys(i).forEach( key => acc.hasOwnProperty(key) ? acc[key].push(i[key]) : acc[key] = [i[key]]);
return acc;
},{});
// take the key and last item from the values
var result = Object.entries(intermediate).map( entry => {
var [key,value] = entry;
return {[key]: value[value.length-1]};
});
console.log(result);

TA貢獻(xiàn)1871條經(jīng)驗 獲得超13個贊
向后循環(huán)可以完成這項工作,將用戶名和最后索引存儲在單獨的字典中。您從右到左循環(huán)數(shù)組。如果用戶不在字典中(即它是它的最后一個條目),則將其添加到字典中;否則它只會繼續(xù)循環(huán)。
我建議以這種方式存儲每個條目以使循環(huán)更容易:
{ userName: 'mickey gray',
value: 500 }
循環(huán)可能是這樣的:
let indexDictionary = {};
for(let i = array.length - 1; i >= 0; i--) {
if(!indexDictionary[array[i].userName]) {
indexDictionary[array[i].userName] = array[i].value;
}
}
添加回答
舉報