gpt4 book ai didi

javascript - 查找满足条件的数组索引的位置

转载 作者:行者123 更新时间:2023-11-30 09:21:22 27 4
gpt4 key购买 nike

我是 ES6 的新手,正在尝试学习如何编写一个函数来查找第一个数组索引号,其中有最多的 0 在一起 - 例如:

var arr = [0,0,1,0,0,0,1,1,0] // should return index 3
var arr = [0,0,1,0,0,0,1,1,0,0,0,0] // should return index 8
var arr = [0,0,1,0] // should return index 0

不知道为什么,但我的尝试只返回一个空数组,而不是一个索引数组,其中数字从 0 变为 1:

var arr = [0,0,1,0,0,0,1,1,0];
function amounts(c, i, arr) {
var zeros = 0, onesTogether = 0, where = [], changes = 0, longest0s;

if (c === 0 && arr[i+1] === 0 || c === 0 && arr[i-1] === 0) {
zeros++;
} else {
longest0s = zeros;
zeros = 0;
changes++;
where.push[i];
}

console.log('longest0s: ' + longest0s + '. changes: ' + changes + '. where: ' + where);
return where;

}
arr.reduce(amounts);

我不知道如何找到最多 0 的位置的开始索引,但无法发现为什么数组为空。有什么想法吗?

这应该返回 [2,6,7] 的数组

[0,0,1,0,0,0,1,1,0]

最佳答案

大体思路:找到最长的0s子串并查看其索引。

你可以试试:

const find = arr => {
const str = arr.join('');
const longest = str.split(1).reduce((a, b) => a.length > b.length ? a : b);
return str.indexOf(longest);
}

console.log(find([0,0,1,0,0,0,1,1,0])); // 3
console.log(find([0,0,1,0,0,0,1,1,0,0,0,0])); // 8
console.log(find([0,0,1,0])); // 0

关于javascript - 查找满足条件的数组索引的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51422070/

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