检查元素是否在数组中两次

时间:2016-10-28 13:07:36

标签: javascript arrays

我需要知道元素是否在数组中两次或多次。

var arr = [elm1,elm2,elm3,elm3,elm4,elm5,elm5,elm5,elm6,elm7] ;
if(elm is in array by many time ){
      // do some code with this element
}else{
      // other stuff ;;
}

有什么建议吗?

2 个答案:

答案 0 :(得分:9)

countInArray函数可能是您的选项

function countInArray(array, what) {
    return array.filter(item => item == what).length;
}

或类似的东西,这可能会更好地理解代码并调整你想要的东西! :

var list = [2, 1, 4, 2, 1, 1, 4, 5];  

function countInArray(array, what) {
    var count = 0;
    for (var i = 0; i < array.length; i++) {
        if (array[i] === what) {
            count++;
        }
    }
    return count;
}

countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3

答案 1 :(得分:-2)

function check(){
var arr =['1','2','3','3','4'];
  for (i=0; i<arr.length;i++){
    for (x=0;x<arr.length;x++){
      if(arr[i]==arr[x] && i != x){
        console.log('SAME ones in ARRAY: '+arr[i]);
      }else console.log('no same ones');
    }
  }
}