Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I remove duplicates in Javascript array with out sorting

So I am making a game that calculates love percentage based on the letters in two peoples names with the word love.

In the code below I am counting the number of times a letter appears in the value array then I want to push this value into the nums Array for each unique letter. However I am not sure how I can get it to not repeat for each time the letter appears in the value array. Also I can not sort the array or the game will not calculate properly.

so for example the below value array should push 3 for s only once into the nums array.

var value =["s", "a", "m", "a", "n", "t", "h", "a", "w", "h", "i", "t", "e", "l", "o", "v", "e", "s", "J", "a", "c", "k", "h", "a", "r", "r", "i", "s"]; 


function trueLoveGame(value){

    var nums=[];

    for(var i =0; i < value.length;i++){
        var count = 0;
        for(var a = 0; a < value.length;a++){
            if(value[i] === value[a]){  
                count++;
            }
            else{

            }
        }   
    }
}
like image 731
Susan Delgado Avatar asked Aug 09 '26 02:08

Susan Delgado


1 Answers

So as it wasn't clear exactly what was required. This should answer both possibilities that I think you could be asking.

var userArray = ["s", "a", "m", "a", "n", "t", "h", "a", "w", "h", "i", "t", "e", "l", "o", "v", "e", "s", "J", "a", "c", "k", "h", "a", "r", "r", "i", "s"];

function unique(array) {
    var unique = [];

    array.forEach(function (value) {
        if (unique.indexOf(value) === -1) {
            unique.push(value);
        }
    });

    return unique;
}

function count(array) {
    var obj = {};

    array.forEach(function (value) {
        obj[value] = (obj[value] || 0) + 1;
    });

    return obj;
}


console.log(userArray);
console.log(unique(userArray));
console.log(count(userArray));

on jsfiddle

like image 123
Xotic750 Avatar answered Aug 11 '26 16:08

Xotic750



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!