0

我需要检查数组以查看数组中是否有任何连续的重复数字并找到它们的位置。

示例 究竟需要什么将清除您的想法

var myCars=[1 ,1 , 2, 3, 5];   O/P:- 1 is repeated at position 0 & 1.

var myCars=[1 ,1 , 2, 5, 5];   O/P:- 5 is repeated at position 3 & 4. Since 5 is maximum number.

var myCars=[5 ,4 , 1, 1, 1];   O/P:- 1 is repeated at position 2 ,3 & 4.

var myCars=[5 ,5 , 1, 1, 1];   O/P:- 1 is repeated at position 2 ,3 & 4. Since 1 is repeated more number of times.

我尝试了多种方法,但找不到最好的方法。最简单的方法是什么?

以下代码我已经尝试过,但它没有给出确切的期望输出。

var myarray = ["John", "Doe", "Smith", "Doe", "Joe"];

var map = {};
var count = myarray.map(function(val) {
    return map[val] = (typeof map[val] === "undefined") ? 1 : map[val] + 1;
});

var newArray = myarray.map(function(val, index) {
    return val + (map[val] != 1 ? ' - ' + count[index] : '');
});

alert(newArray);

假设只有元素在数组中

http://jsfiddle.net/alnitak/Z4dgr/

4

4 回答 4

1

这有效:迭代并检查当前与下一个和上一个项目。将每个项目的匹配计数和匹配索引添加到单独的对象中。

var results = {};
var positions = {};

myarray.forEach(function(item, index) { 

    if ((index > 0 && myarray[index-1] == item) || (index < myarray.length+1 && myarray[index+1] == item)) {
        results[item] = (results[item] || 0) + 1;
        (positions[item] || (positions[item] = [])).push(index);
    }
});

alert(JSON.stringify(results));
alert(JSON.stringify(positions));​

JSFiddle

于 2012-12-03T05:01:03.847 回答
0

此代码完全按照预期工作

http://jsfiddle.net/9mQ2b/11/

<!DOCTYPE html> 
<html> 
<script>
var myarray = ["1", "1", "4", "4", "3"];
var results = {};
var positions = {};
var j = count = -1;
for(i=0; i<=3; i++)
{ 
if (myarray[i] == myarray[i+1])  // check if num are equal
{
if (count != myarray[i])   //check if continuous num are not equal & set starting position..
{ j++; results[j] = myarray[i]; positions[j] = i; count = myarray[i];
}
if (i == 3) //  set last position of last number if last digit 
positions[j+1] = i+1;
}
else
{
if (count == myarray[i])  // set last position of digit
positions[++j] = i;
count = -1;
}
}
alert(JSON.stringify(results));
alert(JSON.stringify(positions));    
</script>
<body> 
</body> 
</html>​
于 2012-12-03T13:06:16.750 回答
0

我要做的是创建一个二维数组进行计数。第一个 simension 将是被计数的项目,第二个 simension 将是该项目的计数。然后做你的比较。填充阵列后。

我选择这个解决方案是因为我喜欢简单、易于理解的编程方法。让生活变得轻松。

于 2012-12-03T05:07:23.977 回答
0

您可以jquery inArray为此使用函数:代码是

var myarray = ["John", "John", "John", "Doe", "Doe", "Smith",
               "John", "Doe", "Joe"];


var str='';var i=0;
$.each(myarray,function()
       {
           str+=myarray[i]+'='+$.inArray(myarray[i],myarray,i)+', ';
           i++;
       })

alert(str);

或在这里测试小提琴http://jsfiddle.net/Z4dgr/2/

于 2012-12-03T05:09:40.723 回答