Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 根据一个属性按字母顺序对数组中的对象排序_Javascript_Arrays_Sorting - Fatal编程技术网

Javascript 根据一个属性按字母顺序对数组中的对象排序

Javascript 根据一个属性按字母顺序对数组中的对象排序,javascript,arrays,sorting,Javascript,Arrays,Sorting,我知道有一个类似的问题,但是当我使用这个方法一步一步地运行时,它跳过了排序 我有一个对象数组,在控制台中看起来像这样: 0:{id: "3645256536754", name: "john", description: "man", children: Array(0)} 1:{id: "8672092533958", name: "alex", description: "man", children: Array(2)} 我必须对它执行forEach,但在此之前,我必须确保它是根据nam

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

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

0:{id: "3645256536754", name: "john", description: "man", children: Array(0)}
1:{id: "8672092533958", name: "alex", description: "man", children: Array(2)}
我必须对它执行
forEach
,但在此之前,我必须确保它是根据
name
属性按字母顺序排列的

我是这样做的:

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

当我一步一步地运行它时,它跳过了这段代码,我不知道为什么。有什么建议吗?

使用@gurvinder372的评论作为影响,您应该执行以下操作:

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

  return textA.localeCompare(textB);
});

简单地
返回textA.localeCompare(textB)