-2

I tried to sort an array of objects. With key and value. I could able to sort with age .but I don't know how to sort with age and score from my object array Any help will be much appreciated

Fiddle

    
    var unsorted = [{
        name: 'Peter',
        age: 0,
        work:'driving',
        score : 20
    }, {
        name: 'John',
        age: 0,
        work:'document',
        score : 30
    }, {
        name: 'Jess',
        age: 46,
        work:'teacxhing',
        score :10
    }, {
        name: 'Alice',
        age: 0,
          work:'singing',
          score:80
    }],
        sortedByAge = sortByKey(unsorted.slice(0), 'age');
    
    /**
     * Get a DOM element by ID
     * @param {String} id
     * @return {Object}
     */
    function $dom(id) {
        return document.getElementById(id);
    }

    /**
     * Sort an array of Objects based on key
     * @param {Array} array
     * @param {String} key
     * @returns {Array}
     */
    function sortByKey(array, key) {
        return array.sort(function (a, b) {
            var x = a[key],
                y = b[key];
            
            if (typeof x === 'string') {
                x = x.toLowerCase();
                y = y.toLowerCase();
                if (!isNaN(x) && !isNaN(y)) {
                    x = parseInt(x, 10);
                    y = parseInt(y, 10);
                }
            }
            return (x > y ? -1 : (x < y ? 1 : 0));
        });
    }
    
    /**
     * Build a HTML String with the people their age
     * @param {Array} array
     * @return {String}
     */
    function getPeople(array) {
        for (var i = 0, len = array.length, returnString = ''; i < len; i ++) {
            returnString += array[i].name + ', ' + array[i].age +',' +array[i].work+','+array[i].score+'<br/>';
        }
        return returnString;
    }

    // Update the DOM
    $dom('sortedByAge').innerHTML = getPeople(sortedByAge);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
Priya
  • 1
  • 3
  • You can *edit* your question to add content. – Pointy Mar 19 '18 at 13:39
  • 3
    `data = { ['workername1',1,2,32],['workername2', 40,20,40],['workername3', 10,50,10]}` is wrong – brk Mar 19 '18 at 13:45
  • Possible duplicate of [Sorting an array of JavaScript objects](https://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects) – Syed Waqas Bukhary Mar 19 '18 at 13:45
  • Your object is malformed, you are probably getting errors no? Please clarify your question with a working data structure and also provide what you have tryed so far – Mathieu de Lorimier Mar 19 '18 at 13:57
  • Surely you don't mean [['workername1', 1, 2, 32], ...]? What you posted here is not a valid JavaScript object. And you cannot sort an object, you need an array for that. – Oscar Paz Mar 19 '18 at 14:01
  • https://jsfiddle.net/39u8q/56/ – Priya Mar 22 '18 at 09:26

2 Answers2

0

iam sure your data are incorrect. json object are using property, e.g: {property_name1: property_value1, property_name2: property_value2} and since your data didn't have property name, i think that you meant its an array of array:

data = [ ['workername1',1,2,32], ['workername2', 40,20,40], ['workername3', 10,50,10] ];

and you can use array sort to do that, e.g:

data.sort(function(smaller, bigger){ return bigger[3] - smaller[3] });

Fal
  • 135
  • 6
0

You can use array#sort to sort first on age and for same age sort on score using b.age - a.age || b.score - a.score

var unsorted = [{ name: 'Peter', age: 0, work:'driving', score : 20 }, { name: 'John', age: 0, work:'document', score : 30 }, { name: 'Jess', age: 46, work:'teacxhing', score :10 }, { name: 'Alice', age: 0, work:'singing', score:80 }];
unsorted.sort((a,b) => b.age - a.age || b.score - a.score);
console.log(unsorted);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51