Javascript使用

时间:2017-12-29 09:51:10

标签: javascript lodash

我试图按季节和年份排序一系列季节,同时删除重复的季节。排序是不够的我想我需要通过正则表达式,但无法完成它

const myStringArray = ["Winter 17", "Summer 13", "Winter 15", "Summer 12", "Winter 17", "Summer 12", "Summer 17"]
     
console.log(_.uniq(myStringArray).sort(function(a, b) {
    return b - a;                                  
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

3 个答案:

答案 0 :(得分:2)

您可以尝试这样:

const myStringArray = ["Winter 17", "Summer 13", "Winter 15", "Summer 12", "Winter 17", "Summer 12", "Summer 17"]

console.log(_.uniq(myStringArray).sort(function(a, b) {
  return b.split(' ')[1] - a.split(' ')[1] || a.localeCompare(b);
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

答案 1 :(得分:0)

您可以按年份排序,然后获取设置季节顺序的已创建数组的索引。要使数组唯一,只需使用新的Set

const myStringArray = [...new Set(["Winter 17", "Summer 13", "Winter 15", "Summer 12", "Winter 17", "Summer 12", "Summer 17"])];
const order = ['Winter', 'Summer', 'Fall', 'Spring'];

myStringArray.sort((a, b) => {
  let s = b.split(/\s/);
  let s1 = a.split(/\s/);
  return Number(s1[1]) - Number(s[1]) || order.indexOf(s[0]) * -1;
});

console.log(myStringArray);

答案 2 :(得分:0)

如果您确定自己的字符串将始终采用<Season YY>格式且数字只出现一次,则可以使用快速简单的正则表达式对desc进行排序:

&#13;
&#13;
const myStringArray = ["Winter 17", "Summer 13", "Winter 15", "Summer 12", "Winter 17", "Summer 12", "Summer 17"]
     
console.log(_.uniq(myStringArray).sort(function(a, b) {
    return +b.match(/\d+/)[0] - +a.match(/\d+/)[0];                                  
}));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;