Home > Blockchain >  How to Sort array of object by this order?
How to Sort array of object by this order?

Time:10-13

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?

CodePudding user response:

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))

CodePudding user response:

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
    }
  })
)

CodePudding user response:

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

  • Related