-2

I would like to sort an array of objects by a certain string value. For example, I have the below array of objects:

const stores = [
{id: 1, name: 'Store1', country: 'USA'},
{id: 2, name: 'Store2', country: 'Canada'},
{id: 3, name: 'Store3', country: 'USA'},
{id: 4, name: 'Store4', country: 'Canada'}
];

I would like to sort that array so all the objects with a country value of 'Canada' is first. I know you can sort by number, but I am not sure how to sort by a string value. How would I go about doing this? Thank you in advance!

0

1 Answer 1

1

You could use the .toSorted() with a custom sorting (which compares two elements of the array and returns a negative number if the first element should come before the second, a positive number if the second element should come before the first, or zero if they are equal.)
In our example: The comparison function checks if the country value of the first object is 'Canada' and the country value of the second object is not 'Canada', in which case it returns -1 to indicate that the first object should come before the second. If the opposite is true, it returns 1. If both objects have the same country value, it returns 0 to indicate that their order should not change.

const stores = [ {id: 1, name: 'Store1', country: 'USA'}, {id: 2, name: 'Store2', country: 'Canada'}, {id: 3, name: 'Store3', country: 'USA'}, {id: 4, name: 'Store4', country: 'Canada'} ];
function sortByCountryFirst(array, country) {
  return array.toSorted((a, b) => {
    if (a.country === country && b.country !== country) {
      return -1;
    } else if (a.country !== country && b.country === country) {
      return 1;
    } else {
      return 0;
    }
  });
}
console.log(sortByCountryFirst(stores, 'Canada'));

Tip: Use .toSorted() to sort an array without mutating the original array! see my answer

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

1 Comment

@navin1551 I am here to help you at any time :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.