-2

I want to remove all the duplicate items in the array and arrange them in order of their occurrence from most to least

["57358e5dbd2f8b960aecfa8c",
"573163a52abda310151e5791",
"573163a52abda310151e5791",
"573163a52abda310151e5791",
"573163a52abda310151e5791",
"573163da2abda310151e5792",
"57358e5dbd2f8b960aecfa8c",
"57358e5dbd2f8b960aecfa8c"
"573163da2abda310151e5792",]

I want like this

["573163a52abda310151e5791",
 "57358e5dbd2f8b960aecfa8c",
 "573163da2abda310151e5792"]

as the 1st one appears the most no of times , then the second one then the 3rd one which apears only once

learner
  • 143
  • 2
  • 3
  • 11

2 Answers2

0

Of course there is a million different approaches, but a rather simple one would be to first count the occurrences of the different items and then sort the unique values based on that:

var input = [
    "57358e5dbd2f8b960aecfa8c",
    "573163a52abda310151e5791",
    "573163a52abda310151e5791",
    "573163a52abda310151e5791",
    "573163a52abda310151e5791",
    "573163da2abda310151e5792",
    "57358e5dbd2f8b960aecfa8c",
    "57358e5dbd2f8b960aecfa8c",
    "573163da2abda310151e5792"
];

var count = {};
input.forEach(function(item) {
    if(count.hasOwnProperty(item)) count[item]++;
    else count[item] = 1;
});

var output = Object.keys(count).sort(function(left, right) {
   if(count[left] < count[right]) return 1;
   if(count[left] > count[right]) return -1;
   return 0;
});
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
0

You can make an array of key-value pairs (key, occurances), like this:

var arr = [];

for (var i = 0; i < myArray.length; i++) {
    if (arr.indexOf(myArray[i]) > -1) {
        // It occured before, search the key-value pair
        // and increment the occurance
        arr.indexOf(myArray[i])[1]++;
    } else {
        // Add to our array
        arr.push({myArray[i], 1});
    }
}

function compare(a, b) {
    if (a[1] < b[1]) return -1;
    else if (a[1] > b[1]) return 1;
    else return 0;
}

arr.sort(compare);

That way, you have total control over your sorting algorithm, and have the exact number of occurances as an added bonus! Hope this helps.

Tim Visser
  • 916
  • 9
  • 28