gpt4 book ai didi

javascript - 数组中相同的值必须放在一起

转载 作者:行者123 更新时间:2023-12-03 04:40:20 24 4
gpt4 key购买 nike

var array1 = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"]

我必须以相同的值必须放在一起的方式来安排它

输出数组应该是

["ddd","aaa","aaa","aaa","eee","fff","fff","bbb","ggg","ccc"]

如何编写这个逻辑?

最佳答案

您可以迭代数组并检查位置,如果与实际元素不同,则将值拼接到较早的位置。

var array = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"],
i = 0, p;

while (i < array.length) {
p = array.indexOf(array[i]);
if (p !== i) {
array.splice(p, 0, array.splice(i, 1)[0]);
}
i++;
}

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

关于javascript - 数组中相同的值必须放在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43120167/

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