我需要检查数组以查看数组中是否有任何连续的重复数字并找到它们的位置。
示例 究竟需要什么将清除您的想法
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);
假设只有元素在数组中