Reputation: 375
How to sort an array from an object ? The code :
let A = [ { text: '故事', value: 'story', },
{ text: '诗歌', value: 'poetry', },
{ text: '励志', value: 'inspirational', }
];
// array B from backend**
let B = {
story: 2,
poetry: 34,
inspirational: 30,
};
I want to get this :
[
{ text: '诗歌', value: 'poetry', },
{ text: '励志', value: 'inspirational'},
{ text: '故事', value: 'story', },
];
Upvotes: 3
Views: 93
Reputation: 33736
Using the function Array.prototype.sort
you can accomplish your desired output.
This B[bV] - B[aV]
will return a value lesser than 0
or greater than 0
or equal to 0
which is what the function sort
is expecting on to locate the elements at the specific index according to their value from object B
.
let A = [{ text: '故事', value: 'story', }, { text: '诗歌', value: 'poetry', }, { text: '励志', value: 'inspirational', }],
B = { story: 2, poetry: 34, inspirational: 30};
A.sort(({value: aV}, {value: bV}) => B[bV] - B[aV]);
console.log(A);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 7368
Simply you can use JavaScript sort function.
Note: When sorting numbers, you can simply use the compact comparison:
Compact Comparison:: myArray.sort((n1,n2) => n1 - n2);
let A = [ { text: '故事', value: 'story', },
{ text: '诗歌', value: 'poetry', },
{ text: '励志', value: 'inspirational', }
];
// array B from backend**
let B = {
story: 2,
poetry: 34,
inspirational: 30,
};
A.sort((a, b) => B[b.value]-B[a.value] );
console.log(A);
Upvotes: 3
Reputation: 3298
Try this, it uses an arrow function and array.sort
:
let A = [{
text: '故事',
value: 'story',
},
{
text: '诗歌',
value: 'poetry',
},
{
text: '励志',
value: 'inspirational',
}
];
// array B from backend**
let B = {
story: 2,
poetry: 34,
inspirational: 30,
};
A.sort((a, b) => B[b.value] - B[a.value]);
console.log(A);
Upvotes: 1
Reputation: 26854
You can use sort()
to arrange the array elements. You can use Number.NEGATIVE_INFINITY
as a default value if the value
does not exist on B
. This will put the undefined value last.
let A = [{"text":"诗歌","value":"poetry"},{"text":"励志","value":"inspirational"},{"text":"故事","value":"story"}];
let B = {"story":2,"poetry":34,"inspirational":30};
A.sort((x, y) => (B[y.value] || Number.NEGATIVE_INFINITY) - (B[x.value] || Number.NEGATIVE_INFINITY));
console.log(A);
Upvotes: 2
Reputation: 57334
You can use an arrow function in array.sort
as a custom comparator. Sorting in reverse order is accomplished by indexing into the B
object to retrieve the sort value for compared elements and subtracting a
's value from b
.
let A = [
{ text: '故事', value: 'story', },
{ text: '诗歌', value: 'poetry', },
{ text: '励志', value: 'inspirational', }
];
let B = {
story: 2,
poetry: 34,
inspirational: 30,
};
const sorted = A.sort((a, b) => B[b.value] - B[a.value]);
console.log(sorted);
Upvotes: 2