0

And Here is the Array:

enter image description here

If someone's result + GMath is more than others I want to place him first in the array.

I'm making an angular app. I need to filter it for the app. If you need the template or the ts file just comment in below.

6
  • Are you wanting to filter (things removed) or sort (everything still there just in some order) or both? Commented Sep 24, 2018 at 14:59
  • place him first in the array. That's not a filter, it s a sort.. So do you just want the array sorting by "result + GMath"? Commented Sep 24, 2018 at 14:59
  • 2
    There is no array here, you can't sort this without an array of items. Commented Sep 24, 2018 at 14:59
  • @Get_Off_My_Lawn: Please check now. I have added the array. Commented Sep 24, 2018 at 15:10
  • @Keith Yes i want to shorting by result + GMath Commented Sep 24, 2018 at 15:10

2 Answers 2

2

What you need to do is use sort to subtract the sum of a from the sum of b like this:

let arr = [
  {result: 5, GMath: 5},
  {result: 2, GMath: 8},
  {result: 4, GMath: 10},
  {result: 1, GMath: 1}
]

arr.sort((a, b) => (b.result + b.GMath) - (a.result + a.GMath))

console.log(arr)

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

2 Comments

@Moumitaakter, be aware that you exclude IE users and people using "old" versions of their more modern browser -> caniuse.com/#feat=arrow-functions
your code does work. But I don't understand arr.sort((a, b) => (b.result + b.GMath) - (a.result + a.GMath)) this line. Could you be more spesific. And why there is a - between two brackets
1
// const obj = { admissionStudents: {...} }; // assuming this is the object to begin with
let keys = Object.keys(obj.admissionStudents);
keys.sort((a, b) => {
  return (obj.admissionStudents[b].result + obj.admissionStudents[b].GMath) - (obj.admissionStudents[a].result + obj.admissionStudents[a].GMath);
});

Now keys will be sorted, so frame the object using this.

New list,

newList = [];
keys.forEach((key) => {
  newList.push(obj.admissionStudents[key]);
});

newList will be the sorted list.

Hope it helps.

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.