簡體   English   中英

從一個數組中刪除元素並將它們添加到一個新數組中

[英]Remove elements from one array and add them to a new array

我有一系列包含世界國家的對象以及一些附加信息,例如

countries = [
  {
    flag: 'assets/flags/angola.svg',
    code: 'AGO',
    name: 'Angola',
    regions: [{
      name: 'Luanda'
    }]
  },
  {
    flag: 'assets/flags/albania.svg',
    code: 'ALB',
    name: 'Albania',
    regions: [{
      name: 'Korça'
    }, {
      name: 'Tirana'
    }, {
      name: 'Gjirokastër'
    }]
  }...

我想將三個我最喜歡的國家提取到一個新數組中,同時將它們從原始數組中刪除,所以我最終得到兩個 arrays 一個用於我最喜歡的國家,一個用於 rest 國家。

我設法通過以下方式實現了這一目標:

public createCountriesList(allCountries: Country[]) {

let topCountries: Country[] = [];
let restOfCountries: Country[];

allCountries.forEach((element) => {
  switch (element.code) {
    case 'HRV':
      topCountries.push(element);
      break;
    case 'AT':
      topCountries.push(element);
      break;
    case 'GER':
      topCountries.push(element);
      break;
  }
});

restOfCountries = allCountries.filter((c) => {
  return !topCountries.includes(c);
});}

它有效,但我想知道是否有更優雅的方法來做到這一點?

根據我的說法,一切似乎都很好......顯然你需要兩個 arrays 一個用於提取的,第二個用於 rest 的國家。

我們可以做的一件事是開關盒。

您可以使用.includes function 代替 switch case。將要提取的國家/地區的名稱存儲在數組中。

const arr = ['HRV','AT','GR']

現在你可以做,

if(arr.includes(element.code)){
//push into new array
} else{
//push into another 
}

您可以做的另一件事是使用.filter function 保存restOfTheCountries 。如果情況不符合上述情況,只需返回 true 即可。

我可能會創建一個單獨的通用 function 用於根據條件拆分數組(使用 ts 因為你是)

const splitArray = <T>(array: Array<T>, matchFunction: (el: T) => boolean) => {
  const matching: T[] = [], nonMatching: T[] = []
  array.forEach(el => matchFunction(el) ? matching.push(el) : nonMatching.push(el))
  return [matching, nonMatching]
}

然后你可以用數組和 function 調用它

const [topCountries, restOfCountries] = splitArray(countries, c => ["HRV", "AT", "GER"].includes(c.code))

那會更具可讀性。 一個更優雅的解決方案是使用該功能( Array.prototype.split )擴展 Array 然后使用countries.split(c => ["HRV", "AT", "GER"].includes(c.code))

您可以只使用常規過濾器來拆分數組:

const isTop = ({code}) => ['HRV','AT','GR'].includes(code);
const topCountries = allCountries.filter(isTop);
const restOfCountries = allCountries.filter((contry) => !isTop(contry));

另一種方式,你可以添加一個屬性來顯示這個國家是否是頂級的,並通過這個鍵過濾

const withTop = countries.map((e) => ({...e, top: ['AGO','AT','GR'].includes(e.code)}));

// {
//   code: "AGO"
//   flag: "assets/flags/angola.svg"
//   name: "Angola"
//   regions: [{…}]
//   top: true
// }

到目前為止,所有建議似乎都是有效的,我最終使用了@Alexandr Belan 的答案,因為它在我的案例中是最直接實現的,我不知道為什么我使用 switch case 而不是像 topCountries ♂️ 那樣的過濾器。 最終代碼(也添加了國家/地區的字母排序)

  const suggestedCountriesList = ['Brazil', 'France', 'Germany'];
    const suggested = ({ name }) => suggestedCountriesList.includes(name);
    const suggestedCountries = allCountries.filter(suggested);
    const otherCountries = allCountries.filter((country) => !suggested(country));

// sort alphabetically
    otherCountries.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
    suggestedCountries.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));


    return [suggestedCountries, otherCountries];

暫無
暫無

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

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