简体   繁体   English

如何在javascript数组中找到相等元素的数量

[英]How to find the number of equal elements in javascript array

I'm new to JavaScript so please help me on this problem: I have array and I want to get the number of same values. 我是JavaScript的新手,所以请帮助我解决这个问题:我有数组,我想获得相同值的数量。 My array is: 我的阵列是:

 var arr = ["red", "blue", "green", "red", "red", "gray"];

I want to output 3 because I have 3 elements red. 我想输出3因为我有3个元素红色。

This is what I have done so far: 这是我到目前为止所做的:

var numberOfSameElements = 0;
var arr = ["red", "blue", "green", "red", "red", "gray"];
for(var i = 1 ; i <arr.length;i++){
if(arr[i] === arr[i-1]){
   numberOfSameElements++;  
 }
}

  console.log(numberOfSameElements);

I keep getting 1. Please tell me what I am doing wrong. 我一直得到1.请告诉我我做错了什么。 Thank you so much! 非常感谢!

You can reduce the array to a hash map to figure out how many of each word there are: 您可以将数组缩减为哈希映射,以确定每个单词的数量:

var words = ["red", "blue", "green", "red", "red", "gray"];
var wordCounts = words.reduce(function(counts, word) {
  counts[word] = (counts[word] || 0)++;
}, { });

console.log(wordCounts);

// >> {
//      red: 3,
//      blue: 1,
//      green: 1,
//      gray: 1
//    }

If you want the name of any words that are duplicated, you can filter the original array down: 如果您想要重复的任何单词的名称,您可以过滤原始数组:

var repeatedWords = words.filter(function(word) {
  return wordCounts[word] > 1;
});

console.log(repeatedWords);

// >> ['red']

Here you've used one loop and checked your current value with it's previous value. 在这里,您使用了一个循环并使用之前的值检查了当前值。 But you need actually two loops. 但实际上你需要两个循环。

First one will pick a value. 第一个将选择一个值。 And second one will match the picked value with all others. 第二个将匹配所选择的值与所有其他值。 I've used a found flag that checks if a duplicate value has already been found or not. 我使用了一个found标志来检查是否已经找到重复的值。 Try this way, 试试这个,

var numberOfSameElements = 0;
var found = false;
var arr = ["red", "blue", "green", "red", "red", "gray"];
for(var i = 0 ; i <arr.length;i++){
    for(var j = 0; j < arr.length; j++){
        if(arr[i] === arr[j] && i != j){
            if(!found){
                numberOfSameElements++;
                found = true;
            }
        }
    }
    found = false;
}

console.log(numberOfSameElements);

jsFiddle 的jsfiddle

If you want to get the max number of duplicates find in the array, you first have to count them all. 如果要在数组中找到最大重复项数,首先必须统计它们。 Then find the maximum repetition number ( fiddle ): 然后找到最大重复次数( 小提琴 ):

function getLargestNumberOfSame(arr) {
    var counterMap = arr.reduce(function (sameMap, item) { // create a map of same values
        if (!sameMap[item]) {
            sameMap[item] = 1;
        } else {
            sameMap[item]++;
        }

        return sameMap;
    }, {});

    var maxValues = Object.keys(counterMap).map(function(key) {  // turn the map into array of max values
        return counterMap[key];
    });

    return Math.max.apply(window, maxValues); // return the maximum value
}
 var numberOfSameElements = 1;
var arr = ["red", "blue", "green", "red", "red", "gray"];
arr = arr.sort();
var last;
for(var i = 0 ; i <arr.length -1 ;i++) {
    //console.log(arr[i],arr[i+1]);
if(arr[i] == arr[i+1]){
   numberOfSameElements++;
   last = arr[i];

 } else { 
    console.log(arr[i],"repert",numberOfSameElements,"times");
    numberOfSameElements=1;
   }

}
console.log(last,"repert",numberOfSameElements,"times");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM