Home > Back-end >  What is the best way to group and then sort an array of strings by their value?
What is the best way to group and then sort an array of strings by their value?

Time:02-28

I have an array of strings like this, however I'm not sure of how to group them, and then sort them. Inititially I used this function group them by unique values, however not sure how to then sort them. I was also wondering if there's a way to do it with a single function. I've attached what the function returns in it's current state.

[
  60777b59b85d3d0eb2f1a13b,
  60777aeeb85d3d0eb2f1a12e,
  60777bacb85d3d0eb2f1a147,
  60778c56f06d4e1b63759fd4,
  60778c56f06d4e1b63759fd4,
  60777486b85d3d0eb2f1a0d5,
  607778adb85d3d0eb2f1a0f6,
  60777ad3b85d3d0eb2f1a12a,
  60777842b85d3d0eb2f1a0e9,
  60777ad3b85d3d0eb2f1a12a,
  60777bacb85d3d0eb2f1a147,
  60777842b85d3d0eb2f1a0e9,
  60777a56b85d3d0eb2f1a11d
]

const countUnique = arr => {
          const counts = {};
          for (var i = 0; i < arr.length; i  ) {
             counts[arr[i]] = 1   (counts[arr[i]] || 0);
          };
          return counts;
       };

enter image description here

CodePudding user response:

just add arr.sort() to the first line of your countUnique function

const countUnique = arr => {
          arr.sort()
          const counts = {};
          for (var i = 0; i < arr.length; i  ) {
             counts[arr[i]] = 1   (counts[arr[i]] || 0);
          };
          return counts;
       };

CodePudding user response:

const countUnique = arr => {
  const counts = {};
  for (var i = 0; i < arr.length; i  ) {
    counts[arr[i]] = 1   (counts[arr[i]] || 0);
  };
  return Object.entries(counts).sort((a, b) => a[1] > b[1] ? -1 : 1).reduce((result, [key, value]) => {
    result[key] = value;
    return result;
  }, {});
};
  • Related