I have an array of strings and weights associated with it as below:
const words = ['abcd', 'aecd', 'abaa', 'abef', 'acdcc', 'acbcc'];
let weights = [2, 1, 3, 4, 6, 5];
I want to sort the words based on their weights in another array in decreasing order. I tried the solution below:
words.sort((a, b) =>
weights.indexOf(b) -
weights.indexOf(a));
Could anyone pls suggest an alternative solution.
thanks
CodePudding user response:
I think the easiest way to approach this would be to combine the words and weights into a single array, then sort that array.
const words = ['abcd', 'aecd', 'abaa', 'abef', 'acdcc', 'acbcc'];
const weights = [2, 1, 3, 4, 6, 5];
const result = words
.map((word, i) => ({ word, weight: weights[i] }))
.sort((a, b) => a.weight - b.weight)
.map(({ word }) => word);
console.log(result);
CodePudding user response:
To understand in detail how things works please refer below code.
const words = ['abcd', 'aecd', 'abaa', 'abef', 'acdcc', 'acbcc'];
let weights = [2, 1, 3, 4, 6, 5];
var weights1 = [];
let words1 = [];
weights.forEach(function(a) {
weights1.push(a);
});
weights.sort(function(a, b) {
return a - b;
});
weights.forEach(function(a) {
words1.push(words[weights1.indexOf(a)]);
});
console.log(words1);
CodePudding user response:
I think you're looking for weights[words.indexOf(b)]
, not weights.indexOf(b)
(although this will only work if the values in words
are unique):
const words = ['abcd', 'aecd', 'abaa', 'abef', 'acdcc', 'acbcc'];
let weights = [2, 1, 3, 4, 6, 5];
words.sort((a, b) =>
weights[words.indexOf(b)] -
weights[words.indexOf(a)]);
console.log(words)