3
3
3tonua2017-06-26 14:57:37
JavaScript
3tonua, 2017-06-26 14:57:37

How to sort objects inside an array by the number of keys?

For example, there is an array

var Array = [{x : 'x', y : 'y'}, {x : 'x'}, {x : 'x', y : 'y', z : 'z'}];

How to sort it correctly so that the output is like this?
[ {x : 'x'}, {x : 'x', y : 'y'}, {x : 'x', y : 'y', z : 'z'}]

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Demian Smith, 2017-06-26
@3tonua

Array = Array.sort(function(a, b) {
  return Object.keys(a).length - Object.keys(b).length;
});

PS
Array is a registered constructor in JS. It's better not to name variables like Object, Array, String, etc. Otherwise, everything will break.

E
Evgeny Kulakov, 2017-06-26
@kulakoff

var arr = [{x : 'x', y : 'y'}, {x : 'x'}, {x : 'x', y : 'y', z : 'z'}];
arr = arr.sort((a, b) => Object.keys(a).length - Object.keys(b).length)
console.log(arr)

N
Nicholas, 2017-06-26
@healqq

array.map(item => ({...item, keysLength: Object.keys(item).length}))
    .sort((a,b) => a.keysLength - b.keysLength)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question