浏览互联网并进行一些测试后,我实际上找不到解决方案。我正在尝试查找最多0在一起的索引。例如,应返回3和6:
var arr1 = [1,0,1,0,0,1,0,0,1,1];
var joined1 = arr1.join(''); // "1010010011"
var ans = joined1.indexOf("00"); // returns 3 - want to return 3 & 6
这应该返回1和5:
var arr2 = [1,0,0,0,1,0,0,0,1,0,0,1,1];
var joined2 = arr2.join(''); // "10001000100111"
var ans2 = joined2.indexOf("000"); // returns 1 - want to return 1 & 5
问题在于indexOf仅返回第一个索引,而不是两个都返回。如何获取返回条件满足的所有实例?谢谢你的帮助
答案 0 :(得分:2)
似乎您在看更多的是字符串操作而不是数组操作。在这种情况下,regex可以为您提供帮助。特别是String.prototype.replace()的函数参数。请注意,下面的代码不会转义特殊的正则表达式字符,例如.
function findAll(string, value) {
var indices = [];
string.replace(new RegExp(value, "g"), function (m, o) {
indices.push(o);
});
return indices;
}
答案 1 :(得分:1)
这有效。从反向搜索字符串,存储索引并获得应在其上再次迭代的子字符串。
function findIndexes(arr, value)
{
var str = arr.join(''), index = 0, result = [];
while(index>-1)
{
index = str.lastIndexOf(value)
index>-1 && (result.push(index), str = str.substring(0,index-1));
}
return result.reverse();
}
console.log(findIndexes([1,0,1,0,0,1,0,0,1,1],"00"));
console.log(findIndexes([1,0,0,0,1,0,0,0,1,0,0,1,1],"000"));
console.log(findIndexes([1,0,1,0,0,1,0,0,1,1],"0000"));
答案 2 :(得分:0)
这里是找到n个连续匹配项的索引的一般解决方案,只是连续匹配项的第一个索引或连续匹配项的所有索引:
function findIndexOfElements(arr, search, times, allkeys) {
var indexs = []
let consecutives = 0;
arr.map((o, i) => {
if (o == search) { //<--we find what we are looking for
if (allkeys) {
indexs.push(i); //<--store all indexes
} else if (consecutives == 0) {
indexs.push(i); //<--store just first index
}
consecutives++;
} else { //<--we don't find what we are looking for
if (consecutives < times && consecutives > 0) {
if (allkeys) {
indexs.splice(-consecutives, consecutives); //<--remove all consecutives
} else {
indexs.splice(-1, 1); //<--remove just the last index
}
}
consecutives = 0;
}
})
return indexs;
}
var arr1 = [1, 0, 1, 0, 0, 1, 0, 0, 1, 1];
var arr2 = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1];
var arr3 = ["cat", "cat", "dog", "cat", "dog", "dog", "cat", "cat"];
//just index of first match
console.log(findIndexOfElements(arr1, 0, 2, false)) //[ 3, 6 ]
console.log(findIndexOfElements(arr2, 0, 3, false)) //[ 1, 5 ]
console.log(findIndexOfElements(arr3, "cat", 2, false)) //[ 0, 6 ]
//all indexes of match
console.log(findIndexOfElements(arr1, 0, 2, true)) //[ 3, 4, 6, 7 ]
console.log(findIndexOfElements(arr2, 0, 3, true)) //[ 1, 2, 3, 5, 6, 7 ]
console.log(findIndexOfElements(arr3, "cat", 2, true)) //[ 0, 1, 6, 7 ]