62493

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. My array is:

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

I want to output 3 because I have 3 elements red.

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. Thank you so much!

Answer1:

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. 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);

<strong>jsFiddle</strong>

Answer2:

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']

Answer3:

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 }

Answer4:

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");

Recommend

  • pandas computation in each group
  • Excel VBA How to populate a multi-dimensional (3d) array with values from multiple excel ranges?
  • What's the syntax to inherit documentation from another indexer?
  • Error in installing package: fatal error: stdlib.h: no such file or directory
  • Primefaces ManyCheckbox inside ui:repeat calls setter method only for last loop
  • Why the SequenceFile is truncated?
  • How to make R's read_csv2() recognise the text characters properly
  • DIV instruction jumping to random location?
  • Get specific string
  • why xml file does not aligned properly after append the string in beginning and end of the file usin
  • htaccess add www if not subdomain, if subdomain remove www
  • Ionic 2 storage is not cleaning up on uninstall - Only for signed APK
  • preg_replace Double Spaces to tab (\\t) at the beginning of a line
  • Mysterious problem with floating point in LISP - time axis generation
  • How to know when stdin is empty if it contains EOF?
  • JSON response opens as a file, but I can't access it with JavaScript
  • Record samples being played with OpenAL
  • Meteor: Do Something On Email Verification Confirmation
  • Extracting HTML between tags
  • MongoDB in PHP using aggregate to group by _id is null not working
  • Deselecting radio buttons while keeping the View Model in synch
  • Nant, Vault & Windows Integrated Authentication
  • Why HTML5 Canvas with a larger size stretch a drawn line?
  • Accessing IRQ description array within a module and displaying action names
  • DirectX11 ClearRenderTargetViewback with transparent buffer?
  • Where to put my custom functions in Wordpress?
  • Updated Ionic CLI but shows previous version (Windows)
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • RestKit - RKRequestDelegate does not exist
  • PHP: When would you need the self:: keyword?
  • WPF Applying a trigger on binding failure
  • Acquiring multiple attributes from .xml file in c#
  • sending mail using smtp is too slow
  • Busy indicator not showing up in wpf window [duplicate]
  • reshape alternating columns in less time and using less memory
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Reading document lines to the user (python)
  • How can I use `wmic` in a Windows PE script?
  • Conditional In-Line CSS for IE and Others?
  • How can I use threading to 'tick' a timer to be accessed by other threads?