Home > database >  How can I sort a array of objects by a parameter inside an objects?
How can I sort a array of objects by a parameter inside an objects?

Time:12-11

For example, I have a array of objects returned by back-end, with positions as string.

[
    {
        "color": "red",
        "position": "SECOND"
    },
    {
        "color": "blue",
        "position": null
    },
    {
        "color": "green",
        "position": "FIRST"
    },
    {
        "color": "pink",
        "position": "THIRD"
    }
]

I need reorganize this array, by key "position", but I need mantein all objects, including nulls in yours original positions (nulls must be after those with position).

[
    {
        "color": "green",
        "position": "FIRST"
    },
    {
        "color": "red",
        "position": "SECOND"
    },
    {
        "color": "pink",
        "position": "THIRD"
    },
    {
        "color": "blue",
        "position": null
    },
]

I tryed use a map with possible positions with slice, but my array stays out of order.

CodePudding user response:

Try searching it in google and also in bing

CodePudding user response:

Is there a way to have different values in the "position" field?

You could try something like this :

let test = [
    {
        "color": "red",
        "position": "SECOND"
    },
    {
        "color": "blue",
        "position": null
    },
    {
        "color": "green",
        "position": "FIRST"
    },
    {
        "color": "pink",
        "position": "THIRD"
    }
]


test.sort((a,b) => a.position > b.position ? 1 : -1)  //for ascending order

test.sort((a,b) => a.position > b.position ? -1 : 1)  //for descending order

But it's just a coincidence that "first", "second" and "third" are in alphabetical order

CodePudding user response:

const input = [
  {
    color: "red",
    position: "SECOND",
  },
  {
    color: "blue",
    position: null,
  },
  {
    color: "green",
    position: "FIRST",
  },
  {
    color: "pink",
    position: "THIRD",
  },
  {
    color: "yellow",
    position: "FOURTH",
  },
];

const sortOrder = [
  "first",
  "second",
  "third",
  "fourth",
  "fifth",
  "sixth",
  "seventh",
  "eighth",
  "ninth",
  "tenth",
];

function doCustomSort(a, b, customSortOrder) {
  if (a.position === null && b.position !== null) {
    return 1;
  } else if (a.position !== null && b.position === null) {
    return -1;
  }

  return (
    sortOrder.indexOf(a.position.toLowerCase()) -
    sortOrder.indexOf(b.position.toLowerCase())
  );
}

console.log(input.sort((a, b) => doCustomSort(a, b, sortOrder)));
  • Related