gpt4 book ai didi

javascript - 比较两个数组并返回一个新数组,其中包含仅在原始数组之一中找到的任何项目

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

[“闪长岩”、“安山岩”、“草”、“泥土”、“粉红色羊毛”、“死灌木”],

[“闪长岩”、“安山岩”、“草”、“泥土”、“死灌木”]应该返回[“粉色羊毛”]

因为“粉红色羊毛不存在于第一个数组中,即 arr1。但它返回一个空数组。此代码仅适用于数字数组。但是当数组仅包含字符串或带数字的字符串时,代码不起作用。

function diff(arr1, arr2) {

var newArray = arr2.concat(arr1); //first joininng both arrays inn one and storing it in newArray

var newestArray = [];

for (var i=0 ; i<newArray.length ; i++) { //NOW COMPARING EACH ELEMENT OF newArray WITH ARR1 AD ARR2 AND PUSHING NOT SAME VALUES TO newestArray
if (arr1.indexOf(newArray[i]) == -1) {
newestArray.push(newArray[i]);

if (arr2.indexOf(newArray[i]) == -1) {
newestArray.push(newArray[i]);
}
}
}

return newestArray.filter(Boolean); //It is returning an empty arrray but it should return "pink wool"
}

diff(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);

最佳答案

此解决方案采用线性方法和一个用于计数的对象。

var array1 = ["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"],
array2 = ["diorite", "andesite", "grass", "dirt", "dead shrub"];

function symmetricDifference(setA, setB) {
var o = {}, result = [];
function count(i, o) {
return function (a) {
o[a] = o[a] || { count: 0, value: a };
o[a].count += i;
};
}

setA.forEach(count(1, o));
setB.forEach(count(-1, o));
Object.keys(o).forEach(function (k) {
if (o[k].count) {
o[k].count = Math.abs(o[k].count);
while (o[k].count--) {
result.push(o[k].value);
}
}
});
return result;
}

document.write('<pre>' + JSON.stringify(symmetricDifference(array1, array2), 0, 4) + '</pre>');

关于javascript - 比较两个数组并返回一个新数组,其中包含仅在原始数组之一中找到的任何项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34837834/

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