gpt4 book ai didi

javascript - 从 1..N 项数组中查找丢失的项

转载 作者:搜寻专家 更新时间:2023-11-01 04:53:27 25 4
gpt4 key购买 nike

我被要求从 1..N 数组中找到缺失的数字。

例如,对于数组:让 numArr = [2,4,6,8,3,5,1,9,10]; 缺少的数字是 7

let numArr=[2,4,6,8,3,5,1,9,10];
numArr.sort(function(a,b){ //sort numArr
return a-b;
});

let newNumArr=[];
for(let i=1;i<=10;i++){
newNumArr.push(i);
}

for(let i=0;i<newNumArr.length;i++){ //compare with new arr
if(newNumArr[i] !== numArr[i]){
console.log('The missing num is:'+newNumArr[i]); //The missing num is:7
break;
}
}

最佳答案

您可以使用MAPFILTER 找出单独数组中缺失的数字

const numArr = [2, 4, 6, 8, 3, 5, 1, 9, 10];
const missingNumberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(number => {
if (!numArr.includes(number)) {
return number;
}
}).filter(y => y !== undefined);

关于javascript - 从 1..N 项数组中查找丢失的项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50269298/

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