Orion
Orion

Reputation: 174

sorting the content of an object with javascript

if I have an object that looks like:

let object = {
  name1 : {
    number : .5,
    otherVar : 'something'
  }, 
  name2 : {
    number : .7,
    otherVar : 'text'
  },
  name3 : {
    number : -.1,
    otherVar : 'some words'
  }
};

how could I sort it by the number value and get an array:[ name3, name1, name2]?

Upvotes: 1

Views: 54

Answers (6)

developer_hatch
developer_hatch

Reputation: 16224

It should do the dirty work, first you flat your object into an array of objects, then you create your custom compare function, finally sort, and voila!

var keys = Object.keys(object);

function compare(a,b) {
  if (object[a].number < object[b].number)
    return -1;
  if (object[a].number > object[b].number)
    return 1;
  return 0;
}
var res = keys.sort(compare);

Upvotes: 0

Barmar
Barmar

Reputation: 780723

Make an array that contains the object properties with the names added to them:

var array = [];
for (var key in object) {
    object[key].name = key;
    array.push(object[key]);
}

Then sort that array by the number:

array.sort((a, b) => a.number - b.number);

Then get the names out of the array:

var sortedNames = array.map(e => e.name);

Full demo:

let object = {
  name1 : {
    number : .5,
    otherVar : 'something'
  }, 
  name2 : {
    number : .7,
    otherVar : 'text'
  },
  name3 : {
    number : -.1,
    otherVar : 'some words'
  }
};

var array = [];
for (var key in object) {
    object[key].name = key;
    array.push(object[key]);
}
array.sort((a, b) => a.number - b.number);
var sortedNames = array.map(e => e.name);
console.log(sortedNames);

Upvotes: 1

Dekel
Dekel

Reputation: 62536

Here is another es6 exampel:

let object = {
  name1 : {
    number : .5,
    otherVar : 'something'
  }, 
  name2 : {
    number : .7,
    otherVar : 'text'
  },
  name3 : {
    number : -.1,
    otherVar : 'some words'
  }
};

let k = Object.keys(object).sort(((a, b) => object[a].number > object[b].number));
console.log(k);

Upvotes: 2

Oleg Markoff
Oleg Markoff

Reputation: 321

var items = [];
items = JSON.parse(object);
}); //will give you an array

function compare(a,b) {
  if (a.number < b.number)
    return -1;
  if (a.number > b.number)
    return 1;
  return 0;
}
items.sort(compare); //array will be sorted by number

Upvotes: 0

Traveling Tech Guy
Traveling Tech Guy

Reputation: 27811

let sorted = Object.keys(obj).map(key => obj[key]).sort((a, b) => a.number - b.number);

Explanation:

  • Object.keys(obj) will return an array of keys ['name1', 'name2'...]
  • .map will turn that array into an array of values
  • .sort takes a compare function and returns the sorted array (see documentation)

Recommendation: don't call your objects object :)

Upvotes: 2

djfdev
djfdev

Reputation: 6037

Here's a one liner:

Object.keys(object).map(key => object[key]).sort((a, b) => a.number - b.number)

Upvotes: 2

Related Questions