【问题标题】:JavaScript sorting array with same item [duplicate]具有相同项目的JavaScript排序数组[重复]
【发布时间】:2018-06-03 17:06:26
【问题描述】:

我正在尝试对数组进行排序。我想对它进行排序,以便对于相同的 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);
});

我得到的错误是 Uncaught (in promise) TypeError: Cannot read property 'push' of undefined at the else statement there.

【问题讨论】:

  • 你能展示你的数组声明吗
  • @programtreasures 你的意思是“arr”还是“filteredlist”?如果为“arr”,则数据之前是从 firebase 检索到的。为简单起见,我只是 console.log 并自己格式化输入,而不是发布整个检索块。
  • @guest176969 您的输入不是数组,而是一堆数组。选择一个!
  • 我已经更新了这个问题。检查屏幕截图:) 我的格式可能有误,对此我深表歉意!
  • 问题是你的existing.filteredlist 文件永远不会被创建

标签: javascript arrays sorting


【解决方案1】:

您可以采用更简单的方法,使用 foreach 循环和对象。

var items = {};

arr.forEach(function(item) {

    if(!items.hasOwnProperty(item.accountID)) {
        items[item.accountID] = [];
    }

    items[item.accountID].push(item.itemName);
});

您可以使用Object.keys(items)获取每个帐户的密钥。

Object.keys(items).forEach(function(account) {
    // account is the accountID

    var accountItems = items[account];
});

【讨论】:

  • 我收到未定义错误消息的 accountID :(
  • 我已经测试过了,它对我有用。问题一定是潜在的承诺。
  • 我设法打印出 arr 中的数据,所以我认为它与承诺无关。
  • 尝试从 itemArray 中删除 [0]
  • 它适用于您放置 const items = {}; 的版本但是,当我放一个 for 循环试图访问“项目”时,什么都没有打印出来。它只打印出排序后的数组及其 accountID 没有 for 循环
【解决方案2】:

这里需要在filteredlist使用前进行初始化

更新代码

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 = [];
                    existing.filteredlist.push(item.itemName);
                } else {
                    items.push(item);
                }
            return items;
            }, []);
            console.log('filtered');
            console.log(result);

这是我的 jsbin 演示 https://jsbin.com/tepedut/edit?js,console

编辑:

根据您的评论,您需要使用accountID 属性对arr 进行排序,您可以使用javascript arr.sort(function(a, b){}); 函数对数组进行排序。

这里是更新的代码

arr.sort(function(a, b){
   if(a.accountID < b.accountID) return -1;
    if(a.accountID > b.accountID) return 1;
    return 0;
});

console.log(arr);

更新了 js bin https://jsbin.com/tepedut/8/edit?js,console

【讨论】:

  • 是否可以将 itemName 打印为所需的输出?因为目前 console.log(result) 也打印出 accountID
  • 检查这个更新的 js bin 添加了 item.itemName 到数组 jsbin.com/tepedut/5/edit?js,console
  • 但如果是这种情况,它只会将每个项目推送到单个数组中,而不管 accountID 是什么。有什么方法可以将它分开,以便每个 accountID 根据所需的输出打印出来?
  • 您还需要在结果中返回 accountID 吗?
  • 不不,我只需要根据所需的输出部分按每个 accountID 排序的项目
猜你喜欢
  • 2021-09-30
  • 1970-01-01
  • 2021-03-04
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多