0

Hello everyone I need a function so that i can sort an array of objects alphabeticaly by a certain property value.

Let say i have this array:

var myObj = [{Name: 'John'},
             {Name: 2.10},
             {Name: 'Andrew'},
             {Name: 10},
             {Name: 2.101}
            ];

The result should be 2.10, 2.101, 10, 'Andrew', 'John'. I need this sorting beacause in my program the Name property can be either a name as 'John' or and IP (like 1.0.0.14) or even a MAC address(97948453855)...

I have managed some sorting but it doesnt seem to work perfectly for both strings and numbers.

Thank you!

9
  • 1
    What is the basis of your sorting? Algorithm? Commented Mar 2, 2017 at 18:31
  • Show what you tried so we can see where you went wrong. Commented Mar 2, 2017 at 18:33
  • Please provide your code. Commented Mar 2, 2017 at 18:33
  • 1
    Possible duplicate of Sort array of objects by string property value in JavaScript Commented Mar 2, 2017 at 18:34
  • 1
    A correct duplicate is probably how to sort alpha numeric content. Commented Mar 2, 2017 at 18:39

1 Answer 1

3

You could check for string and use the delta as first result part, or take the nummerical delta or at last the string comparison.

var array = [{ Name: 'John' }, { Name: 2.10 }, { Name: 'Andrew' }, { Name: 10 }, { Name: 2.101 }];
            
array.sort(function (a, b) {
    return (typeof a.Name === 'string') - (typeof b.Name === 'string') || a.Name - b.Name || a.Name.localeCompare(b.Name);
});

console.log(array);

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.