1

I have the below array. Did console.log for the array and it is as below

(3) [Array(4), Array(4), Array(4)]
0 ["jackpot", "cherry", "bar", "pear"]
1 ["raspberry", "raspberry", "raspberry", "lemon"]
2 ["plum", "crown", "lemon", "jackpot"]

I tried the below and in console i just see my array and 1 next to it

var counts = {};
currentResults.forEach(function(obj) {
var key = JSON.stringify(obj)
counts[key] = (counts[key] || 0) + 1
})
console.log(counts);

How can i search and find the duplicated values in the above array/object and count how many duplicated items I have with javascript/jquery?

Anahit Ghazaryan
  • 664
  • 10
  • 23
  • 2
    Duplicates per child array, or duplicates within all child arrays? Also, please show what you've tried. At the moment this is a 'write my code for me' question, which is likely to be downvoted and/or closed – Rory McCrossan Sep 20 '17 at 11:11
  • 1
    possible duplicate of:- https://stackoverflow.com/questions/10541068/javascript-count-duplicates-within-an-array-of-objects – Alive to die - Anant Sep 20 '17 at 11:13
  • Duplicates within all child arrays @RoryMcCrossan. I tried so many ways that's why not sure which one to add – Anahit Ghazaryan Sep 20 '17 at 11:13
  • An off topic question for everyone: What does `(counts[key] || 0) + 1`mean? – Reporter Sep 20 '17 at 11:21
  • Just so you know, your answer you had was pretty close. The reason you got 1 next to each array is because obj is an array and you were trying to compare arrays to arrays, so counts[obj] would be 0 + 1 giving you 1 after each line. You just needed `obj.forEach` loop after `currentResults.forEach` function and making your key equal to that function loop. Also no need to JSON.stringify. – Matt Sep 20 '17 at 13:54

4 Answers4

1

Here you go with a solution

var data = [["jackpot", "cherry", "bar", "pear"], ["raspberry", "raspberry", "raspberry", "lemon"],["plum", "crown", "lemon", "jackpot"]];

var key = {};
for(var i=0; i<data.length; i++){
  for(var j=0; j<data[i].length; j++){
    if(typeof key[data[i][j]] === 'undefined'){
      key[data[i][j]] = 1;
    } else {
      key[data[i][j]] = parseInt(key[data[i][j]]) + 1;
    }
  }
}

console.log(key);

I assumed your data as an array of array. Loop through both the array & for every item, kept an count in the form of a JSON (key: value).

Key as item & value is the count.

Updated Solution to get the duplicate items

var data = [["jackpot", "cherry", "bar", "pear"], ["raspberry", "raspberry", "raspberry", "lemon"],["plum", "crown", "lemon", "jackpot"]];

var key = {};
var duplicate = [];
for(var i=0; i<data.length; i++){
 for(var j=0; j<data[i].length; j++){
   if(typeof key[data[i][j]] === 'undefined'){
     key[data[i][j]] = 1;
    } else {
     key[data[i][j]] = parseInt(key[data[i][j]]) + 1;
      if(parseInt(key[data[i][j]]) >= 3 && duplicate.indexOf(data[i][j]) == -1){
       duplicate.push(data[i][j]);
      }
    }
  }
}

console.log(duplicate);

Updated Solution for finding duplicates within child array

var data = [["jackpot", "cherry", "bar", "pear"], ["raspberry", "raspberry", "raspberry", "lemon"],["plum","jackpot", "crown", "lemon", "jackpot", "jackpot"]];

var key = {};
var duplicate = [];
for(var i=0; i<data.length; i++){
 key = {};
 for(var j=0; j<data[i].length; j++){
   if(typeof key[data[i][j]] === 'undefined'){
     key[data[i][j]] = 1;
    } else {
     key[data[i][j]] = parseInt(key[data[i][j]]) + 1;
      if(parseInt(key[data[i][j]]) >= 3 && duplicate.indexOf(data[i][j]) == -1){
       duplicate.push(data[i][j]);
      }
    }
  }
}

console.log(duplicate);

Hope this will help you.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
  • Hey @Shiladitya yes is what i needed. I just need to get only the element value which is duplicated 3 times not all but is very useful and exact snippet i need. How i can retrive the key value only when number is 3 or more? – Anahit Ghazaryan Sep 20 '17 at 11:22
  • @AnahitGhazaryan I've updated the answer, have a look. – Shiladitya Sep 20 '17 at 11:28
  • Yes @Shiladitya thank you for the good snippet. can you pls explain what this means duplicate.indexOf(data[i][j]) == -1 ? – Anahit Ghazaryan Sep 20 '17 at 11:33
  • `duplicate.indexOf(data[i][j]) == -1` this part will check if the item is already exists in duplicate array or not. `-1` means the item is not present in duplicate array. – Shiladitya Sep 20 '17 at 11:34
  • Aha ok. Thank you very much @Shiladitya for the good idea and useful snippet – Anahit Ghazaryan Sep 20 '17 at 11:37
  • Welcome @AnahitGhazaryan :) – Shiladitya Sep 20 '17 at 11:40
  • One more question pls @Shiladitya. If i will want to check specifically each child array how much duplicates have and have values in seprate how i can achive that result with current snippet? Thanks in advancce – Anahit Ghazaryan Sep 20 '17 at 12:05
  • @AnahitGhazaryan I've updated the answer for finding child duplicates, have a look. – Shiladitya Sep 20 '17 at 13:58
  • Hey @Shiladitya thanks for the snippet. Am trying to find a way how i can check the count of each elements in child array and then check if for example there is 1 jackpot on the first, 1 on the second and 1 on the third array. Any idea? Thanks – Anahit Ghazaryan Sep 21 '17 at 06:17
0

use this :)

var test=[["jackpot", "cherry", "bar", "pear"], ["raspberry", "raspberry", "raspberry", "lemon"],["plum", "crown", "lemon", "jackpot"]];
var counts = {};
for(var i=0;i<test.length;i++)
test[i].forEach((x)=> { counts[x] = (counts[x] || 0)+1; });
console.log(counts);

enter image description here

Aymen
  • 1,476
  • 18
  • 28
0

You can iterate over each array element inside your main array and push unique values in a new array and if the value already exists than you got a duplicate and store it in result array.

Here I am not writing the whole code as I can not see what you have tried.

You can use this method to check if an element already exist in new array

arr.indexOf()

Edit: A better approach would be to iterate over each array element inside your main array and store them as a property of an object and their count as the value of the property. At the end your object would be something like this:

{
  "raspberry": 3,
  "lemon" : 2
}
Rohit Agrawal
  • 1,496
  • 9
  • 20
0

You can check duplications for each arrays or you can merge arrays in one array for checking all arrays.

        var array1 = ["jackpot", "cherry", "bar", "pear"];
        var array2 = ["raspberry", "raspberry", "raspberry", "lemon"];
        var array3 = ["plum", "crown", "lemon", "jackpot"];

        var parentArray = [array1, array2, array3];
        var joinedArray = [];

        // ForEach Array
        var duplicatedElementsForEachArray = [];
        parentArray.forEach(function (childArray) {

            // Merge Arrays in joinedArray
            joinedArray = joinedArray.concat(childArray);

            var duplicatedElements = 0;
            var sortedChildArray = childArray.slice().sort(); // Sorting each Arrays
            var i = 0, l = sortedChildArray.length - 1;
            while (i < l) { if (sortedChildArray[i] == sortedChildArray[i + 1]) duplicatedElements++; i++; } // If i. and (i+1). elements are same, this will be duplication
            duplicatedElementsForEachArray.push(duplicatedElements);
            console.log(duplicatedElements);
        });

        // Joined Array, you can check duplications for merged array with same algorithm
        var sortedJoinedArray = joinedArray.slice().sort();
        var duplicatedElementsForJoinedArray = 0;
        var i = 0, l = sortedJoinedArray.length - 1;
        while (i < l) { if (sortedJoinedArray[i] == sortedJoinedArray[i + 1]) duplicatedElementsForJoinedArray++; i++; }
        console.log(duplicatedElementsForJoinedArray);
Murat Acarsoy
  • 294
  • 3
  • 10