假设以下是我们的对象-
var details = [ { studentId: 100, name: "John" }, { studentId: 110, name: "Adam" }, { studentId: 120, name: "Carol" }, { studentId: 130, name: "Bob" }, { studentId: 140, name: "David" } ];
要对上面的键-值对对象进行排序,请使用sort()
。
以下是代码-
var details = [ { studentId: 100, name: "John" }, { studentId: 110, name: "Adam" }, { studentId: 120, name: "Carol" }, { studentId: 130, name: "Bob" }, { studentId: 140, name: "David" } ]; details = details.sort(function (obj1, obj2) { return obj1.name.localeCompare(obj2.name); }); console.log(details);
要运行上述程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo253.js。
输出结果
这将在控制台上产生以下输出-
PS C:\Users\Amit\javascript-code> node demo253.js [ { studentId: 110, name: 'Adam' }, { studentId: 130, name: 'Bob' }, { studentId: 120, name: 'Carol' }, { studentId: 140, name: 'David' }, { studentId: 100, name: 'John' } ]