0

Here we have 2 types of variables in an array and one being an integer while the other being a string , I am trying to sort the array via alphabetical order or by the length of the string but it keeps detecting the integer over the string first.

    const val=[{
      x:"second",
      y:2
     },{
      x:"first",
      y:1
    }];   
    function compare(a,b){return b.length-a.length};
    val.sort(compare);
    console.log(val);

4
  • 2
    Objects don't have a length property unless explicitly defined (which is not the case here) Commented Jul 12, 2018 at 7:52
  • 1
    Possible duplicate of (stackoverflow.com/q/979256/9775003) Commented Jul 12, 2018 at 7:55
  • "variables in an array": you mean (property) values. Variables are different things. Commented Jul 12, 2018 at 7:58
  • yea i meant properties* value thx Commented Jul 12, 2018 at 8:22

2 Answers 2

1

    const val=[{
      x:"second",
      y:2
     },{
      x:"first",
      y:1
    }];   
    function compare(a,b){return a.x.length-b.x.length};
    val.sort(compare);
    console.log(val);

You need to compare the property and not the object. Also you might want to handle all the scenarios of -1, 0 and 1 for the callback. I'll leave that to you. Have a look at existing similar questions.

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

Comments

0

you are finding the length of the object not the object key x so you need to change your a.length to a.x.length and b.length to b.x.length

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.