invrt
invrt

Reputation: 709

Iterate through a prop, but sort by a different prop React JS

I have this function that sorts the array by the Defect(string), however, I want to iterate through the Count(number).

getCount() {

let arr = this.state.rows
  let arr2 = arr.filter(qc => qc.BinsByDayByOrchardsQCs.length > 0).map((qc) =>
      qc.BinsByDayByOrchardsQCs.map((qc2) =>
          qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => qc3).sort((a, b) 
              => a.Defect < b.Defect ? -1 : a.Defect > b.Defect ? 1: 0)));

        return arr2
    };

This function returns

0: {BinsByDayByOrchardsQCsID: "-LbiHz7tuuJH71I_4IKw", Defect: "Bruise", Count: 2, BinsByDayByOrchardsQCs: null}
1: {BinsByDayByOrchardsQCsID: "-LbiHz7tuuJH71I_4IKw", Defect: "Hail damage", Count: 0, BinsByDayByOrchardsQCs: null}
2: {BinsByDayByOrchardsQCsID: "-LbiHz7tuuJH71I_4IKw", Defect: "Scuff", Count: 2, BinsByDayByOrchardsQCs: null}
3: {BinsByDayByOrchardsQCsID: "-LbiHz7tuuJH71I_4IKw", Defect: "Sunburn", Count: 1, BinsByDayByOrchardsQCs: null}

My array is sorted, however inside my original function I would like to iterate over Count, not the whole object.

It would look like something like this..

 qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => qc3.Count).sort((a, b) 
               => a.Defect < b.Defect ? -1 : a.Defect > b.Defect ? 1: 0)));

But I'm currently getting "property 'Defect' does not exist on type 'number'

It should also be noted that I'm using TypeScript with React

my interface
BinsByDayByOrchardsQCs: { BinsByDayByOrchardsQCsDefects: { Defect: string, Count: number }[] }[]

Upvotes: 0

Views: 50

Answers (1)

Tekill
Tekill

Reputation: 1201

The reason you are getting this error is because when you use map it will essentially output an array that only contains the values of count

qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => qc3.Count)

Outputs:

[2, 0, 2 , 1]

You should first sort and then map, try it the other way:

qc2.BinsByDayByOrchardsQCsDefects.sort((a, b) => a.Defect < b.Defect ? -1 : a.Defect > b.Defect ? 1: 0))).map((qc3) => qc3.Count);

Also, here you are sorting strings so I am not sure if that'll work properly but at least you should not get the error about the property not existing.

UPDATE:

I had missed in your post that you are using Typescript, try this to see if it works as suggested by this post

qc2.BinsByDayByOrchardsQCsDefects.sort((a, b) => a.Defect < b.Defect ? -1 : a.Defect > b.Defect ? 1: 0))).map((qc3) => (qc3 as any).Count);

Another suggestion would be to try with qc3["Count"] instead of qc3.Count, Typescript somehow does not perceive this thing equally...

Upvotes: 1

Related Questions