过滤以JavaScript中的字母开头的列表元素

时间:2016-11-06 20:41:03

标签: javascript arrays

我正在尝试将以'N'开头的列表元素整理成新列表。 为什么这不起作用?

const countries = ['Norway', 'Sweden',  'Denmark', 'New Zealand'];

function firstN(){
  for (let i=0;i<countries.length;i++){
    countries[i].startsWith("N")
    }
}

let startsWithN = countries.filter(firstN())

8 个答案:

答案 0 :(得分:6)

这与@ adeneo的答案大致相同,只是一点点:

const countries = ['Norway', 'Sweden',  'Denmark', 'New Zealand'];

const startsWithN = countries.filter((country) => country.startsWith("N"));

console.log(startsWithN);

// Output: [ 'Norway', 'New Zealand' ]

答案 1 :(得分:1)

您根据条件进行过滤,指定的函数会根据该条件返回truefalse

&#13;
&#13;
const countries = ['Norway', 'Sweden', 'Denmark', 'New Zealand'];

function firstN(item) {
  return item.toLowerCase().indexOf('n') === 0;
}

let startsWithN = countries.filter(firstN);

console.log(startsWithN)
&#13;
&#13;
&#13;

答案 2 :(得分:1)

非常简单:

&#13;
&#13;
const countries = ['Norway', 'Sweden',  'Denmark', 'New Zealand'];

let startsWithN = countries.filter(function (country) {
  return country[0].toLowerCase() === 'n';
});

console.log(startsWithN)
&#13;
&#13;
&#13;

答案 3 :(得分:0)

countries.filter(s => s.toLowerCase().indexOf("n") == 0)

答案 4 :(得分:0)

如果预期结果是一个新数组,其中只包含以countries开头的"N"元素,则可以调整现有javascript以在firstN内创建数组,并传递输入数组到firstN.push()元素,在if循环中将for条件循环到新数组return新数组

&#13;
&#13;
const countries = ['Norway', 'Sweden', 'Denmark', 'New Zealand'];

function firstN(arr, letter) {
  for (let i = 0, res = []; i < arr.length; i++) {
    if (arr[i].startsWith(letter)) res.push(arr[i])
  }
  return res
}

let startsWithN = firstN(countries, "N");

console.log(startsWithN);
&#13;
&#13;
&#13;

要对原始数组进行排序,您可以使用.sort()

&#13;
&#13;
const countries = ['Norway', 'Sweden', 'Denmark', 'New Zealand'];

function sortByFirstLetter(letter) {
  return function(a, b) {
    let [firstLetterA, firstLetterB] = [a[0], b[0]];
    return firstLetterA === letter && firstLetterB !== letter ? -1 : 1
  }
}

countries.sort(sortByFirstLetter("N"));

console.log(countries);
&#13;
&#13;
&#13;

答案 5 :(得分:0)

仍然很苛刻:

const countries = ['Norway', 'Sweden',  'Denmark', 'New Zealand'];

const startsWithN = countries.filter(/./.test.bind(/^N/));

console.log(startsWithN);

这将函数传递给filter RexExp.prototype.test的curry版本:它将上下文(this)设置为/^N/,即匹配的正则表达式以大写字母N开头的字符串。结果类似于:

const startsWithN = countries.filter(country => /^N/.test(country));

答案 6 :(得分:0)

const countries = ['Norway', 'Sweden',  'Denmark', 'New Zealand'];

const startsWithN = countries.filter((country) => country[0]==='N');

console.log(startsWithN);

答案 7 :(得分:0)

const freinds = ['Salman', 'Asad',  'Shahrukh', 'Aman'];
const startsS = freinds.filter((freind) => freind.startsWith("s"));
console.log(startsS);

输出:

<块引用>

['萨尔曼','沙鲁克']