Mohamed Ouedraogo
Mohamed Ouedraogo

Reputation: 31

Sorting js object by using objects props (name)

I need you to help me for training purpose. I try to learn Js and Ts by exploiting an external public API. When I fetch my data and show them correctly, I want now to add the sorting functionality. To get to this, I need to first sort my objects by name. I read the array.sort() function sort by default string. It's my starting point.

But my issue, is that I don't know how the sort function can be use in my case. Maybe the fact that my array element are object, or something else, but I don't know. I need your help to let me figure out what can I done to use this function.

The above code is how I create and fetch my array

import ListItem from "../ListItem/ListItem";
import { Pokemon } from "../../interfaces/flower";

type Props = {
  items: Flower;
};
const List = ({ items }: any) => {
  return (
    <>
      {items.map((item, index) => {
        return (
          <>
            <ListItem key={index} data={item}></ListItem>
          </>
        );
      })}
    </>
  );
};

export default PokemonList;

And the following is the Flower detail

import {FlowerDetail} from "./flowerDetail";
export type FLower = {
  name: string,
  url: string,
  FLowerDetail: FLowerDetail[]
}

PS:apologize my english, it's not my native language, still learning XD

Upvotes: 0

Views: 58

Answers (2)

deepak thomas
deepak thomas

Reputation: 1180

It is better to sort the list in the js part then you have received the data and then pass it to the UI for the render. So for sort of the array in js part can be done by calling

let orgArray = []
.....
items = orgArray.slice();
items.sort((a,b)=>{
   // Use toUpperCase() to ignore character casing
  const nameA = a.name.toUpperCase();
  const nameB = b.name.toUpperCase();

  let comparison = 0;
  if (nameA > nameB) {
    comparison = 1;
  } else if (nameA < nameB) {
    comparison = -1;
  }
  return comparison;
})

As a result the original array is not affected but the sort and you can use it again. For more reference on sort refer this link

Sorting in the render causes unnecessary staring on the browser

Upvotes: 1

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

You need to include a sort callback function. This function takes 2 arguments, call them a and b. This callback function can make use of string::localeCompare

  items.sort((a, b) => a.name.localeCompare(b.name)).map(...)

Upvotes: 3

Related Questions