如何在foreach修剪后对数组对象进行排序



下面有一些数组对象。我想在foreach循环后按id对数据进行排序,我使用的是sort(),但有错误。如何对数据进行排序并按顺序循环?

$(document).ready(function(){
const data = [
{
id : 3,
name: 'John'
},
{
id : 1,
name: 'Doe'
},
{
id : 2,
name: 'Lorem'
},
]
data.forEach((item, index) => {  
item.sort(function(a, b) {
$('.data').append(`<ul>
<li>${item.id}</li>
</ul>`);
});
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="data"></div>

先尝试排序,然后再进行forEach((:

$(document).ready(function() {
const data = [{
id: 3, name: 'John'
},
{
id: 1, name: 'Doe'
},
{
id: 2, name: 'Lorem'
},
];
data.sort((a, b) => a.id - b.id).forEach((item) => {
$('.data').append(`<ul>
<li>${item.id}</li>
</ul>`);
});  
})

查看异常消息

item.sort is not a function TypeError: item.sort is not a function

将调用sort((方法的值转换为数组,或者确保只在有效数组上调用sort方法

根据问题的数据格式,建议您先排序,然后排序forEach

$(document).ready(function() {
const data = [
{id: 3, name: 'John'},
{id: 1, name: 'Doe'},
{id: 2, name: 'Lorem'},
];
// Sorts the data array by id in ascending order
data.sort((a, b) => a.id - b.id);

// Pass in each element of the sorted array and execute the given function once
data.forEach(({id}) => {
$('.data').append(`<ul><li>${id}</li></ul>`);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="data"></div>

但如果实际上数据格式更复杂,例如多个数组元素的数组,并且每个数组元素代表一组li,则可以参考以下代码片段

$(document).ready(function() {
const data = [
[
{id: 3, name: 'John'},
{id: 1, name: 'Doe'},
{id: 2, name: 'Lorem'}
],
[
{id: 2, name: 'Lorem'},
{id: 1, name: 'Doe'},
{id: 3, name: 'John'}
]
];
// Sorts the data array by id in ascending order
data.sort((a, b) => a.id - b.id);
// Pass in each array element of the array and execute the given function once
data.forEach(item => {
const $ul = 
$('<ul/>').append(
item
.sort((a, b) => a.id - b.id)
.map(({id}) => $(`<li>${id}</li>`))
);
$('.data').append($ul);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="data"></div>

最新更新