0

Input:

var arr = [{ fName: "a" }, { fName: 1 }, { fName: "A" }];

Expected Output

var arr = [{ fName: 1 }, { fName: "A" },{ fName: "a" }];

supposed key fName is a employee name and we want to sort this object [1,'A','a'] like this but in object form. how to do this?

1

3 Answers 3

1

You can give precedence to numbers over strings checking the typeof variable, and returning -1 or 1 accordingly:

compareFn(a, b) return value sort order
> 0 sort a after b
< 0 sort a before b
=== 0 keep original order of a and b

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

const arr = [{ fName: "a" }, { fName: 3 }, { fName: "A" }, { fName: 1 }];

console.log(
  arr.sort((a, b) => {
    if (typeof a.fName === 'number' && typeof b.fName !== 'number') {
      return -1
    }
    if (typeof a.fName !== 'number' && typeof b.fName === 'number') {
      return 1
    }
    if (a.fName < b.fName) {
      return -1
    }
    if (a.fName > b.fName) {
      return 1
    }
    if (b.fName === a.fName) {
      return 0
    }
  })
)

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

Comments

1

You just need to come up with a proper sorting function.

  1. It should compare numbers with strings
  2. It should make upper case first.

const sortByFName = (a, b) => a.fName
  .toString()
  .localeCompare(
    b.fName.toString(), 'en', {
      caseFirst: 'upper'
    }
  )

const result = [{
  fName: "a"
}, {
  fName: 1
}, {
  fName: "A"
}].sort(sortByFName)

console.log(JSON.stringify(result))

Comments

0

You can use Array.prototype.sort to sort an array using any comparison code you want.

For example:

objArray.sort((a, b) => {
    // Some code for comparison
});

Learn more about the sort function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

1 Comment

I interpret the question as asking what to put in the "code for comparison" to produce the desired order.

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.