本文介绍了根据一个属性按字母顺序对数组中的对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一个类似的问题,,但是当我使用此方法逐步运行时,它会跳过排序.

I know that there is a similar question, Javascript - sort objects in an array alphabetically on one property of the array, but when I run step by step using this method it jumps over the sort.

我在控制台中有一个看起来像这样的对象数组:

I have an array of objects which looks like this in console:

0:{id: "3645256536754", name: "john", description: "man", children: Array(0)}
1:{id: "8672092533958", name: "alex", description: "man", children: Array(2)}

我必须在其上执行forEach,但是在确保基于name属性的字母顺序之前,必须确保它是按字母顺序排列.

I must do a forEach on it but before I must be sure that it is in alphabetical order based on the name property.

我是这样做的:

myArray.sort(function (a, b) {
    var textA = a.name.toUpperCase();
    var textB = b.name.toUpperCase();
    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
})

当我逐步运行它时,它会跳过这段代码,我不知道为什么.有什么建议吗?

When I run it step by step it jumps over this piece of code, I don't know why. Any suggestions?

推荐答案

使用@ gurvinder372的注释作为影响力,您应该执行以下操作:

Using the comment by @gurvinder372 as influence, you should do the following:

myArray.sort(function (a, b) {
  var textA = a.name.toUpperCase();
  var textB = b.name.toUpperCase();

  return textA.localeCompare(textB);
});

这篇关于根据一个属性按字母顺序对数组中的对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 15:36