我正在尝试对数组进行排序。我想对其进行排序,以便对于相同的 accountID,我将所有项目存储为数组项目。输入示例:
[{accountID: "-Ks8mWWekpN2BfOFcdbS", itemName: "Petrol Charges At Esso"}],
[{accountID: "-Ks8mWWekpN2BfOFcdbS", itemName: "Hylo Lubricant Eye Drops 10ml"}],
[{accountID: "-Ks8mWWekpN2BfOFcdbS", itemName: "Genteal Gel, Sterile Lubricant Eye Gel, 10g"}],
[{accountID: "-Ks8mWWekpN2BfOFcdbS", itemName: "Genteal Gel, Sterile Lubricant Eye Gel, 10g"}],
[{accountID: "-Ks8mWWekpN2BfOFcdbS", itemName: "Blink Intensive Tears Protective Eye Drops 0.4mlx20"}],
[{accountID: "-Ks8mWWekpN2BfOFcdbS", itemName: "Palmers White And Even Dark Circles Eye Treatment Cream 15ml"}],
[{accountID: "-Ks8mWWq445Uao_9sgNn", itemName: "Sensitive Pro-relief With Whitening Toothpaste 110g"}],
[{accountID: "-Ks8mWWq445Uao_9sgNn", itemName: "2 In 1 Pure Breath Toothpaste"}],
[{accountID: "-Ks8mWWq445Uao_9sgNn", itemName: "Antibackterial Mouthwash 200ml"}],
[{accountID: "-Ks8mWWq445Uao_9sgNn", itemName: "Akira 1.7l Jug Kettle Jk1718c"}],
[{accountID: "-Ks8mWWq445Uao_9sgNn", itemName: "Duracell Alkaline Batteries Aaa 12s"}],
[{accountID: "-Ks8mWWq445Uao_9sgNn", itemName: "Osram Led Star Classic A100 Light Bulb - Frosted Warm White 10.5w/827"}],
[{accountID: "-Ks8mWWq445Uao_9sgNn", itemName: "Sharks Fin Soup With Crab Meat And Cordyceps"}],
[{accountID: "-Ks8mWWq445Uao_9sgNn", itemName: "Chilli Fried Rice With Shrimps"}],
需要打印到文本文件的输出:
['Petrol Charges At Esso', 'Hylo Lubricant Eye Drops 10ml', 'Genteal Gel, Sterile Lubricant Eye Gel, 10g', 'Blink Intensive Tears Protective Eye Drops 0.4mlx20', 'Palmers White And Even Dark Circles Eye Treatment Cream 15ml'],
['Sensitive Pro-relief With Whitening Toothpaste 110g', '2 In 1 Pure Breath Toothpaste', 'Antibackterial Mouthwash 200ml', 'Akira 1.7l Jug Kettle Jk1718c', 'Duracell Alkaline Batteries Aaa 12s', 'Osram Led Star Classic A100 Light Bulb - Frosted Warm White 10.5w/827', 'Sharks Fin Soup With Crab Meat And Cordyceps', 'Chilli Fried Rice With Shrimps'],
我的 JavaScript 代码:
// for simplicity purpose, I do not post the chunk where I resolve the promise.
promiseKey.then((arr) => {
console.log(arr);
var result = arr.reduce(function(items, item) {
var existing = items.find(function(i) {
return i.accountID === item.accountID;
});
if (existing) {
existing.filteredlist.push(item.itemName);
} else {
items.push(item);
}
return items;
}, []);
console.log('filtered');
console.log(result);
});
我收到的错误是未捕获( promise 中)TypeError:无法在 else 语句中读取未定义的属性“push”。
最佳答案
您可以采用更简单的方法,使用 foreach 循环和对象。
var items = {};
arr.forEach(function(item) {
if(!items.hasOwnProperty(item.accountID)) {
items[item.accountID] = [];
}
items[item.accountID].push(item.itemName);
});
您可以使用Object.keys(items)
获取每个帐户的 key 。
Object.keys(items).forEach(function(account) {
// account is the accountID
var accountItems = items[account];
});
关于JavaScript 对具有相同项目的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47917878/