1

Today I came across with one issue, I don't it this issue is coming because of code or bugs in Javascript. I tried to sort object array, which is like this

const array = [{
text:'one'
count:5
},
{
text:'two'
count:5
},
{
text:'three'
count:5
},
{
text:'four'
count:5
}]

Now I need to sort the object array based on the count index. I tried with these piece of code

Array.prototype.sortBy = function (p) {
          return this.slice(0).sort(function (a, b) {
            return (a[p] > b[p]) ? 1 : (a[p] < b[p]) ? -1 : 0;
          });
  }
   console.log(array.sortBy('count'))

Here sorting is working fine when I have object array length as less than 100, but won't work when I have more than that length. I tried with some Npm packages also. But it doesn't work. Help me

2
  • 1
    What exactly do you mean by "won't work"? Are you getting errors? Is it not sorted at all? Or badly? Please be specific and ideally create a minimal reproducible example. It works for me with a length of 200: jsfiddle.net/khrismuc/bdfgs624 Commented Nov 19, 2019 at 20:33
  • 1
    I can't reproduce it Commented Nov 19, 2019 at 20:34

1 Answer 1

2

You're making it too complicated for no gain, you can just rely on the .sort method

Here is a codepen to show it working with 500 elements, just to be sure

const array = [{
    text: 'one',
    count: 3
  }, {
    text: 'two',
    count: 1
  }, {
    text: 'three',
    count: 2
  }, {
    text: 'four',
    count: 4
}];

let sorted = array.sort((a, b) => a.count - b.count);

console.log(sorted);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.