-1

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.

3

2 Answers 2

0

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

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

2 Comments

This is pure coincidence that FIRST, SECOND and THIRD listed in this order happen to be alphabetically sorted as well. Add an element with position: "FOURTH" and you'll see where this blows up.
I did say that also...
0
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)));

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.