-1

i am working on Angular7 and Typescript, i want to sort array of dict in typescript. here is my data :

{
  "data": [
    {
      "name": "Azad University",
      "tedad": 80
    },
    {
      "name": "University of Science and Technology",
      "tedad": 14
    },
    {
      "name": "University of Kurdistan",
      "tedad": 30
    }
  ]
}

i want to sort this data by tedad key. how can i do this?
i see this code on stackoverflow but i dont know how to change it that works:

items.sort(function(first, second) {
  return second[1] - first[1];
});
1

2 Answers 2

0

In ts file:

    sample = {
        "data": [
            {
                "name": "Azad University",
                "tedad": 80
            },
            {
                "name": "University of Science and Technology",
                "tedad": 14
            },
            {
                "name": "University of Kurdistan",
                "tedad": 30
            }
        ]
    }
constructor(){
    this.sample.data.sort(function(first, second) {
                return (first.tedad - second.tedad);
            });
            console.log(this.sample);
}
Sign up to request clarification or add additional context in comments.

Comments

0

parameters in Array.prototype.sort() are elements of the array. You can access by property of theirs.

const items = {
  "data": [{
      "name": "Azad University",
      "tedad": 80
    },
    {
      "name": "University of Science and Technology",
      "tedad": 14
    },
    {
      "name": "University of Kurdistan",
      "tedad": 30
    }
  ]
}

const sorted = items.data.sort((prev, curr) => prev.tedad - curr.tedad);

console.log(sorted)

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.