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

时间:2018-07-19 11:55:09

标签: javascript

我是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]

2 个答案:

答案 0 :(得分:3)

一般思路:找到最长的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

答案 1 :(得分:1)

您可以使用两个辅助对象lastresult,它们具有indexcount的属性,并更新计数器或重置last对象。

function getIndex(array) {
    var last,
        result;

    array.forEach((v, i) => {
        if (v) {
            last = undefined;
            return;
        }
        last = last || { count: 0, index: i };
        last.count++;
        if (!result || result.count < last.count) {
            result = last;
        }
    });
    return result.index;
}

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

相关问题