Remove repetition of letters from a Javascript array

Remove repetition of letters from a Javascript array
0

#1

Hi

I am trying to show the number of times letters are occurring in an array but don’t want to repeat any letters occurring more than once. For example

arrSorted = [‘a’,‘a’,‘b’,‘b’,‘b’,‘c’,‘c’]
currently the result is coming like:
a x 1
a x 2
b x 1
b x 2
b x 3
c x 1
c x 2

instead the result should be:
a x 2
b x 3
c x 2

The code I have written is:

        var currentValue = arrSorted[0]; //a
        var currentIndex;
        var counter = 0;
        for (var i = 0; i < arrSorted.length; i++) { //6
          currentIndex = arrSorted[i]; // aaceinn
          if (currentValue === currentIndex) {//a===a
            counter++; // 12
            console.log(currentValue + " x " + counter); // ax1 ax2 nx2
          }
          else {
            counter = 0; //
            currentValue = arrSorted[i]; //c
            counter++; //1
            console.log(currentValue + " x " + counter); //nx1
          }
        }

any help or suggestions?


#2

Have you tried using an object ? I find them useful for this situation.

const counter = {};
const words = ["cow","cow","cow","cow","cow","cow"];

for (let i = 0; i < words.length; i++) {
  
    const word = words[i]; // "cow"
    
    if (!counter.hasOwnProperty(word)) {
        // if counter doesn't have a property named "cow", add it to counter and assign 1 to the property "cow" 
        counter[word] = 1;
        
    } else {
       // else, increment the value of "cow" by 1
       counter[word]++; 
    }
}

console.log(counter["cow"] + " cows"); // 6 cows


#3

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.


#4

Thanks @ArielLeslie for letting me know, i’ll explore the link as I’m very new to the forum :+1:


#5

It can look as simple as this:

arr.filter((item,i) => i === arr.indexOf(item))

But I think you should learn the splice function. You can loop and, if arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i]) you can splice that index out of the array.
You can also just create a new empty array, do a loop in the old array and if newArray.indexOf(oldArray[i]) === -1 - if the new array doesn’t have that letter, you can push it in and then return the newArray.