gpt4 book ai didi

javascript排序和重新映射数组

转载 作者:行者123 更新时间:2023-11-30 07:12:58 24 4
gpt4 key购买 nike

我正在使用以下代码(由 JQuery Javascript Sort Array by Highest Count 提供)将字符串列表从最高到最低排序:

var items = {}, sortableItems = [], i, len, element, listOfStrings; 

listOfStrings = JSON.parse(the_chems);


for (i = 0, len = listOfStrings.length; i < len; i += 1)
{
if (items.hasOwnProperty(listOfStrings[i])) {
items[listOfStrings[i]] += 1;
} else {
items[listOfStrings[i]] = 1;
}
}

for (element in items)
{
if (items.hasOwnProperty(element)) {
sortableItems.push([element, items[element]]);
}
}

sortableItems.sort(function (first, second)
{
return second[1] - first[1];
});

代替这种类型的数组输入

["red", "red", "red", "blue", "blue"]

返回

[ [ "red", 3 ], [ "blue", 2 ] ]

我想使用像这样的数组

[["red","apple"], ["red","chilli"], ["red","melon"], ["blue","ocean"], ["blue","eyes"]]

然后返回

[["red", 3, ["apple","chilli","melon"]], ["blue", 2, ["blue","ocean"]]

最佳答案

您可以使用哈希表并将结果收集到一个数组中。

var array = [["red", "apple"], ["red", "chilli"], ["red", "melon"], ["blue", "ocean"], ["blue", "eyes"]],
hash = Object.create(null),
result = [];

array.forEach(function (a) {
if (!hash[a[0]]) {
hash[a[0]] = [a[0], 0, []];
result.push(hash[a[0]]);
}
hash[a[0]][1]++;
hash[a[0]][2].push(a[1]);
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript排序和重新映射数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45801450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com