How to sort according to category and element's key to display

116 Views Asked by At

I have a trouble finding a solution.

Right now, I am building an app with react.

In the one of the pages, I need to ask a user for multiples inputs from pre-defined options.

for instance enter image description here

or enter image description here

the problem is that pre-defined options may change always. it could be totally different countries food.

whenever use choose a option, i am adding the option in the array declared by useState()

const [selectedFoods, setSelectedFoods] = useState([], []);

and when the new food is added, it would look like this

[
  0: {id:3, food: "Western food", level: 1 },
  1: {id:7, food: "Italian food", level: 2 },
  2: {id:1, food: "Chinese food", level: 2 },
  3: {id:6, food: "Italian food", level: 1 },
  4: {id:0, food: "Chinese food", level: 1 },
]

the problem right now here is that, i am added new element always at the end. it is not sorted at all.

and when I added a new option, I would like to display under the selection dropdown box as below...

Chinese Food:
   Chinese Food: level1, Chinese Food: level2

Italian Food:
   Italian Food: level1, Italian Food: level2

Western Food:
   Western Food: level1

what i was trying to do was create a component that takes an array as props and populate each food levels

const FoodComponent = () => {
  return (
    <div>
      <h3>{props.title}</h3>
      <div>
        <span>{props.title}: </span>{props.contents.map(content => content.id)}
      </div>
    </div>
  )
}

and loop through array, but sort according to an element's level as well as category

{
  selectedFoods.map(food => {
    // call the component that created above 
  })
}

I thought creating a new array that contains unique food category as elements would help, but i still could not figure out after this step.

Please someone provide me a solution to this.

Thank you very much in advance.

1

There are 1 best solutions below

0
On

If you wanna sort wrt food and level.

var arr=[
 {id:3, food: "Western food", level: 1 },
 {id:7, food: "Italian food", level: 2 },
 {id:1, food: "Chinese food", level: 2 },
 {id:6, food: "Italian food", level: 1 },
 {id:0, food: "Chinese food", level: 1 },
]
arr.sort((a,b)=>a.food>b.food?1:-1).sort((c,d)=>c.level>d.level?1:-1).sort((a,b)=>a.food>b.food&&a.level<b.level?1:-1)
console.log(arr)