簡體   English   中英

返回包含包含特定單詞的字符串的新數組

[英]Return new array containing strings which contain specific words

我試圖獲取一個數組並返回一個僅包含姓氏為“ Smith”的數組。

我正在嘗試對此進行過濾,並且已經嘗試了一段時間,但完全沒有想法。

請查看下面的代碼,我知道我已經走了,讓我知道在哪里可以獲得更好的結果? 多謝你們!

const smiths = arr.filter(function(smith) {
  let nameSplit = smith.split(' ')
  return nameSplit === "Smith" 
 });                               
return smiths;

例:

arr = ['Penelope Smith', 'Charlotte Smither'] returns ['Penelope Smith']

@slouisa您幾乎擁有了它,只是缺少了拆分數組的索引。

const lastNameToFilter = "smith";
const smiths = arr.

 arr = ['Penelope Smith', 'Charlotte Smither']; const lastNameToFilter = "Smith".toLowerCase(); const smiths = arr.filter(function(fullname) { let nameSplit = fullname.split(' '); let lastNameIndex = 1; return nameSplit[lastNameIndex].toLowerCase() === lastNameToFilter; }); console.log(smiths); 

filter(function(smith) {
    let nameSplit = smith.split(' ');
    let lastNameIndex= 1;
    return nameSplit[lastNameIndex].toLowerCase() === lastNameToFilter;
});                               
return smiths;

您可以使用localeCompare做類似的事情以區分大小寫等:

 var arr = ['Penelope Smith', 'Charlotte Smither', 'John smith'] const smiths = (a, s) => a.filter(x => x.split(' ')[1] .localeCompare(s, 'en', {sensitivity: 'base'})==0) console.log(smiths(arr, 'Smith')) 

您可以采用的另一種方法是通過endsWithtoLowerCase

 var arr = ['Penelope Smith', 'Charlotte Smither', 'John smith', 'Mark DeSmith'] const smiths = (a,s) => a.filter(x => x.toLowerCase().endsWith(` ${s.toLowerCase()}`)) console.log(smiths(arr, 'Smith')) 

請注意, endsWith在IE中不支持

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM