根据长度过滤和排序字符串数组?

时间:2018-09-07 05:46:12

标签: javascript arrays string algorithm sorting

例如,我有一个数组:

let arr=["a","bc","de","fgh","i","jkl"];

我想:

  1. 选择所有长度> = 2
  2. 的字符串
  3. ,然后将其排序,直到第一笔最长的字符串,即我想要的结果

    [“ fgh”,“ jk”,“ bc”,“ de”]

我尝试过:

let arr=["a","bc","de","fgh","i","jkl"];
let newArr=[];
for(let s of arr){
  if(s.length>=2){
    newArr.push(s);
  }
}
newArr.sort(function(a,b){
  return a.length<b.length;
});
//newArr should become ["fgh","jk","bc","de"] now

,其中包含多行代码。有没有类似的算法:

let arr=["a","bc","de","fgh","i","jkl"];
let newArr=[];
for(let s of arr){
  if(s.length>=2){
    //push it in to a suitable position
  }
}
//newArr should become ["fgh","jk","bc","de"] now

哪个newArr自然成为排序后的数组?我应该如何写“将其推入合适的位置”?

4 个答案:

答案 0 :(得分:0)

您可以使用.filter().sort()

let arr = ["a","bc","de","fgh","i","jkl"];

let result = arr.filter(({ length }) => (length >= 2))
                .sort((s1, s2) => s2.length - s1.length);

console.log(result);

答案 1 :(得分:0)

您可以使用Array#filter来代替使用for..of循环进行手动过滤。

此外,在Array#sort的情况下,比较函数期望数字不是布尔值。因此,返回值应该是b.length - a.length而不是a.length < b.length

这是我编写代码的方式:

let arr=["a","bc","de","fgh","i","jkl"];

var resultArray = arr.filter(function(t) {
  return t.length >= 2;
}).sort(function(a, b) {
  return b.length - a.length;
});

console.log(resultArray);

//newArr should become ["fgh","jk","bc","de"] now

答案 2 :(得分:0)

您可以使用filter()来取长度大于或等于2的物品。

.filter(i => i.length >= 2);

let arr=["a","bc","de","fgh","i","jkl"];
let newArr = arr.filter(i => i.length >= 2).sort((a,b) => a.length < b.length);
console.log(newArr);

答案 3 :(得分:0)

let arr = ["a","bc","de","fgh","i","jkl"];

让结果 = arr.filter(({ length }) => (length >= 2)) .sort((s1, s2) => s2.localeCompare(s1));

console.log(结果);