gpt4 book ai didi

javascript - 如何比较nodejs中的两个数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:10:24 26 4
gpt4 key购买 nike

假设我有两个数组

["a", "b", "c"]

["c", "a", "b"]

比较这两个数组并查看它们是否相等的最佳方法是什么(对于上述场景,它们应该相等)

最佳答案

function compareArrays(array1, array2) {
array1 = array1.slice();
array2 = array2.slice();
if (array1.length === array2.length) { // Check if the lengths are same
array1.sort();
array2.sort(); // Sort both the arrays
return array1.every(function(item, index) {
return item === array2[index]; // Check elements at every index
}); // are the same
}
return false;
}

console.assert(compareArrays(["a", "b", "c"], ["c", "a", "b"]) === true);

关于javascript - 如何比较nodejs中的两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22812681/

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