Javascript Case Insensitive Sort objects containing undefined 作为值

标签 javascript arrays sorting

我有一个对象数组

说,

var fruits = [
   {name:'apple', capital:'sample'},
   {name:'Tomato', capital:'sample'},
   {name:'jack fruit', capital:'sample'},
   {name:undefined, capital:'sample'},
   {name:'onion', capital:'sample'},
   {name:'Mango', capital:'sample'},
   {name:'Banana', capital:'sample'},
   {name:'brinjal', capital:'sample'}
];

我需要按name 升序排列数组

  1. 对象的name中可能包含undefined
  2. 对象name可能是大写和小写的混合(所以一定是大小写 不敏感搜索)

如果数组有undefined,那么那个对象应该被推到排序列表的末尾。

预期输出

var fruits = [
   {name:'apple', capital:'sample'},
   {name:'Banana', capital:'sample'},
   {name:'brinjal', capital:'sample'},
   {name:'jack fruit', capital:'sample'},
   {name:'Mango', capital:'sample'},
   {name:'onion', capital:'sample'},
   {name:'Tomato', capital:'sample'},
   {name:undefined, capital:'sample'}
];

最佳答案

const fruits = [
   { name: 'apple', capital: 'sample' },
   { name: 'Tomato', capital: 'sample' },
   { name: 'jack fruit', capital: 'sample' },
   { name: undefined, capital: 'sample' },
   { name: undefined, capital: 'sample' },
   { name: undefined, capital: 'sample' },
   { name: 'onion', capital: 'sample' },
   { name: 'Mango', capital: 'sample' },
   { name: 'Banana', capital: 'sample' },
   { name: 'brinjal', capital: 'sample' }
];

const res = fruits.sort(function (a, b) {
  if (a.name === undefined) return 1;
  if (b.name === undefined) return -1;
  if (a.name === b.name) return 0;
  return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1;
});

console.log(res);

关于Javascript Case Insensitive Sort objects containing undefined 作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27036369/

相关文章:

unix - unix中以下三个排序命令有什么区别?

javascript - jquery模态超时后自动显示

javascript - 全局助手正在覆盖 meteor handlebars 模板中的本地上下文

Python 列表作为变量名

java - 在 Java DIY 中克隆对象及其内部数组

java - 在 Java 中排序和显示数组中的条目

c# - 通过查看每个对象自己的路径对多个对象集合进行排序

JavaScript 正则表达式匹配平衡结构而不关心不平衡结构

javascript - Web 组件,添加 Shadow DOM 事件?

javascript - 用不同标签的对象中的数组汇总数组