var taskList =[
{completed:false,task:"to home work"},
{completed:true,task:"test"},
{completed:true,task:"app"},
{completed:false,task:"doing work"},
{completed:false,task:"sleeping"},
{completed:true,task:"to do"},
{completed:true,task:"to home work"},
{completed:false,task:" work"},];
这是一个列表,如下所示
COMPLETED TASK IMCOMPLE TASK
test to home work
app doing work
to do sleeping
to home work work
现在,我想按字母顺序对每个列表进行排序-逐个排序而不影响其他列表
like
如果我想对完成的任务进行排序,则只需对列表进行排序就不要碰到不完整的任务。
答案 0 :(得分:0)
您可以使用sort方法,而忽略对指定完成值的任务进行排序。
在此示例中,您可以将 true 传递给 sortTasks 函数以对已完成的任务进行排序,并 false 对未完成的任务进行排序。>
var taskList =[
{completed:false,task:"z"},
{completed:true,task:"d"},
{completed:true,task:"c"},
{completed:false,task:"y"},
{completed:false,task:"x"},
{completed:true,task:"b"},
{completed:true,task:"a"},
{completed:false,task:"w"},];
function sortTasks(isCompleted) {
return taskList.sort((a,b) => {
if ((a.completed !== isCompleted) || (b.completed !== isCompleted)) return 0;
if (a.task > b.task) return 1;
if (b.task > a.task) return -1;
});
}
//console.log(sortTasks(true)); // sort completed tasks only
// console.log(sortTasks(false))); // sort incomplete tasks only
var newArray = sortTasks(true).filter(a => a.completed);
console.log(newArray);