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', },
];
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);
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);
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);
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);
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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.