0

So I have data.js where I stored my JSON... It looks like this:

[
    {
        name: 'Adam Doe',
        city: 'New York',
        mark: [8,10,10,10]
    },
    {
        name: 'Catlyn Stronk',
        city: 'Las Vegas',
        mark: [2,2,2,2,2,3,3,3,4]
    },
    {
        name: 'Anna Doe',
        
        city: 'Michigan',
        mark: [10,8,8,4,3,2]
    }
]

How can I make an array and put somebody with the highest score on top? So since Adam Doe will have the highest score 9.5 he should be first on the list and so on ... I am working in React.js

1
  • (If it's in a JS file I don't think it's JSON) Commented Jan 4, 2021 at 14:15

1 Answer 1

5

You can create an avg function and then sort the array based on that average.

const people = [
    {
        name: 'Adam Doe',
        city: 'New York',
        mark: [8,10,10,10]
    },
    {
        name: 'Catlyn Stronk',
        city: 'Las Vegas',
        mark: [2,2,2,2,2,3,3,3,4]
    },
    {
        name: 'Anna Doe',
        
        city: 'Michigan',
        mark: [10,8,8,4,3,2]
    }
]

const avg = (arr) => arr.reduce((acc, el) => acc + el, 0) / arr.length;

people.sort((a, b) => avg(b.mark) - avg(a.mark));

console.log(people);

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

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.