簡體   English   中英

查找最后匹配出現的索引

[英]Find index of last matching occurrence

我有要按字母順序添加的variables數組和下一個變量。 它是 AZ,然后是 AA、AB、AC 等等。所以當下一個變量是E我想將它添加到長度為 1 的字母末尾,如果下一個變量是AC我會在末尾添加它在 length=2 等字母上。我嘗試用 findIndex 來做,但它返回第一次出現,而不是最后一次,並且lastIndexOf接受值,而在我的情況下,它應該是給定長度的最后一個元素。

 let variables = ['A', 'B', 'C', 'D', 'AA', 'AB']; const nextVariable = 'E'; const idx = variables.findIndex(x => x.length === nextVariable.length); variables.splice(idx, 0, nextVariable); console.log(variables); // should be ['A', 'B', 'C', 'D', 'E', 'AA', 'AB']

您可以使用自定義排序函數並測試每個值的字母順序和長度。

function mySort(a, b) {
  if(a.length == b.length) {
    return a.localeCompare(b);
  } else {
    return a.length - b.length;
  }
}

添加新值后,您可以使用此函數對數組進行排序:

variables.sort(mySort);

您可以只查找比要插入的變量的第一個變量,如果它不存在( findIndex返回 -1),則添加到數組的末尾:

 let variables = ['A', 'B', 'C', 'D', 'AA', 'AB']; let nextVariable = 'E'; let idx = variables.findIndex(x => x.length > nextVariable.length); variables.splice(idx < 0 ? variables.length : idx, 0, nextVariable); // should be ['A', 'B', 'C', 'D', 'E', 'AA', 'AB'] console.log(variables); nextVariable = 'AC'; idx = variables.findIndex(x => x.length > nextVariable.length); variables.splice(idx < 0 ? variables.length : idx, 0, nextVariable); // should be ['A', 'B', 'C', 'D', 'E', 'AA', 'AB', 'AC'] console.log(variables);

 let variables = ['A', 'B', 'C', 'D', 'AA', 'AB']; const nextVariable = 'E'; variables[variables.length] = nextVariable variables = variables.sort((x,y) => x.length<y.length ? -1 : x.length==y.length ? x.localeCompare(y) : 1) console.log(variables);

暫無
暫無

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

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