1

If I have a JavaScript object like this:

var data = {
 words: ["you", "me", "foo", "bar"],
 numbers: [ 160 ,   20,   100,   80]
};

Is there a way to sort the properties based on value? So that I end up with

var data = {
 words: ["you","foo","bar", "me" ],
 numbers: [160,   100,  80,  20]
};
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
  • You can make a small sorting function on the second array and apply the same change on the first array, but my question is, why do you use two arrays to associate things ? data { you:160, foo;100, ... } could do the trick right ? – Vollfeiw Apr 09 '21 at 11:04
  • 1
    `CTRL + SHIFT + I` (open your console), copy your `object like this` and press enter. You will get `Uncaught SyntaxError: Unexpected token ','`. This is not a valid JS object. Please, edit your question with a valid JS object – Bruno Francisco Apr 09 '21 at 11:04
  • Fixed the syntax error appologies – Emmett Cowan Apr 09 '21 at 11:30
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – mert dökümcü Apr 09 '21 at 11:46
  • What have you tried so far to solve this on your own? – Andreas Apr 09 '21 at 11:55

3 Answers3

0

var data = {
    words: ["you", "me", "foo", "bar"],
    numbers: [160, 20, 100, 80]
};

// Mapping data
var mData = data.words.reduce(function (op, key, index) {
    op[key] = data.numbers[index];
    return op;
}, {});

data.numbers.sort(function (a, b) { return b - a; });
data.words.sort(function (a, b) { return mData[b] - mData[a]; });

console.log(data);
Wazeed
  • 1,230
  • 1
  • 8
  • 9
0

Would look like the OP wants the "order of the words to be based on the order of the numbers"

So to sort words we have to define the weight of each word accordingly by creating an object named words_and_numbers_Mapping. the structure looks like this

{"you":160,"me":20,"foo":100,"bar":80}

var data = { words: ["you", "me", "foo", "bar"],
             numbers: [160 ,  20,  100,  80]};
             
var words_and_numbers_Mapping = data.words.reduce((acc, word, index) => {
    acc[word] = data.numbers[index];
    return acc;
}, {});
data.words.sort((a, b) => words_and_numbers_Mapping[b] - words_and_numbers_Mapping[a]);
data.numbers.sort((a, b) => b - a);

console.log(data);
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
-1

First of all, your object is not a valid object. I will modify the object to be a valid object to give you a guideline on how to solve this.

var data = {
 words: ["you","foo","bar", "me" ],
 numbers: [160,   100,  80,  20]
};

Then we can use a sort function:

data.words = data.words.sort();
data.numbers = data.numbers.sort((a, b) => a - b)

if you wouldn't like to use ES6 syntax you can do:

data.words = data.words.sort();
data.numbers = data.numbers.sort(function (a, b) {
  return a - b;
})
Bruno Francisco
  • 3,841
  • 4
  • 31
  • 61