How can I sort my array data
Here is my structure data
array -> object -> array
I want to sort By tags if tags not empty it should be display first
"data": [
{
"id": 2
"name": "product2",
"tags": [],
},
{
"id": 3,
"name": "product",
"tags": [
{
"id": 3,
"name": "Promoion product",
}
],
},
{
"id": 1,
"name": "product",
"tags": [
{
"id": 4,
"name": "new product",
}
],
},
]
I want my output look like this
"data": [
{
"id": 3,
"name": "product",
"tags": [
{
"id": 3,
"name": "Promoion product",
}
],
},
{
"id": 1,
"name": "product",
"tags": [
{
"id": 4,
"name": "new product",
}
],
},
{
"id": 2
"name": "product2",
"tags": [],
},
]
tags [] should be the last one I try to use lodash but still not working
Just sort descending by tags length
obj.data.sort((a, b) => b.tags.length - a.tags.length); console.log(obj.data);
<script> const obj = { "data": [ { "id": 2, "name": "product2", "tags": [], }, { "id": 3, "name": "product", "tags": [ { "id": 3, "name": "Promoion product", } ], }, { "id": 1, "name": "product", "tags": [ { "id": 4, "name": "new product", } ], }, ] }; </script>
You could sort by checking the length and move only empty tags to bottom and leave the rest unsorted.
var data = [{ id: 2, name: "product2", tags: [] }, { id: 3, name: "product", tags: [{ id: 3, name: "Promoion product" }] }, { id: 1, name: "product", tags: [{ id: 4, name: "new product" }] }]; data.sort((a, b) => !a.tags.length - !b.tags.length); console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
只需按标签长度对其进行排序:
const formatedData = data.sort((a,b) => b.tags.length - a.tags.length))
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.