簡體   English   中英

嘗試將一個數組中的項與另一個數組中的項進行匹配,但第一項被省略

[英]Attempting to match items in one array to items in another array but first item gets omitted

嘗試使用 javascript 將歌曲名稱數組排序為具有匹配藝術家的嵌套數組。 在下面的代碼中有示例 arrays 向您展示正在發生的事情的示例。 由於某些嵌套的 arrays 的某些原因,第一首歌沒有被推送到它。 不知道為什么。 我認為這與artistIndex ,但我不確定如何解決它。 這是控制台 output:文本

artistIndex = 0

tempPlaylist = [
    '1 - a',
    '2 - a',
    '2 - a',
    '3 - a',
    '3 - b',
    '3 - c',
    '4 - a',
    '5 - a',
    '5 - b',
    '6 - a',
]

artistsNested = [
    ['1'],
    ['2'],
    ['3'],
    ['4'],
    ['5'],
    ['6'],
]

for (let song of tempPlaylist) {
    artistSongSplit = song.split(' - ');
    artistName = artistSongSplit[0];
    songName = artistSongSplit[1];

    if (artistName.toUpperCase() === artistsNested[artistIndex][0].toUpperCase()) {
        artistSongSplit = song.split(' - ');
        artistsNested[artistIndex].push(songName)

    } else if (artistName.toUpperCase() != artistsNested[artistIndex][0].toUpperCase()) {
        artistIndex += 1
    }
}
console.log(artistsNested)

您可以通過創建一個以藝術家姓名為關鍵字的中間Map來簡化這一點。 然后只需訪問 map 中的相關“藝術家”並將每首“歌曲”推送到引用的數組即可。

 const tempPlaylist = ['1 - a', '2 - a', '2 - a', '3 - a', '3 - b', '3 - c', '4 - a', '5 - a', '5 - b', '6 - a']; const artistsNested = [['1'], ['2'], ['3'], ['4'], ['5'], ['6']]; const map = new Map(artistsNested.map(([a]) => [a.toUpperCase(), [a]])); for (const track of tempPlaylist) { const [artist, song] = track.split('-').map((s) => s.trim()); if (map.has(artist.toUpperCase())) { map.get(artist.toUpperCase()).push(song); } } const result = [...map.values()]; console.log(result);

上面的代碼片段在創建Map 時描述了藝術家姓名,並為每個子數組創建了新的子數組,以免覆蓋artistsNested數組,但如果您確實想在適當的位置對其進行變異,您可以簡單地維護對原始嵌套 arrays 的引用。

 const tempPlaylist = ['1 - a', '2 - a', '2 - a', '3 - a', '3 - b', '3 - c', '4 - a', '5 - a', '5 - b', '6 - a']; const artistsNested = [['1'], ['2'], ['3'], ['4'], ['5'], ['6']]; // keep references to original nested arrays in Map let map = new Map(artistsNested.map((a) => [a[0].toUpperCase(), a])); for (const track of tempPlaylist) { const [artist, song] = track.split('-').map((s) => s.trim()); if (map.has(artist.toUpperCase())) { map.get(artist.toUpperCase()).push(song); } } // pushes to the nested arrays in place console.log(artistsNested);

或者,要在不使用中間查找表的情況下就地改變 ArtistsNested 數組,您可以使用find()查找相關的“藝術家”子數組,如果存在則推送到它。

 const tempPlaylist = ['1 - a', '2 - a', '2 - a', '3 - a', '3 - b', '3 - c', '4 - a', '5 - a', '5 - b', '6 - a']; const artistsNested = [['1'], ['2'], ['3'], ['4'], ['5'], ['6']]; for (const track of tempPlaylist) { const [artist, song] = track.split('-').map((s) => s.trim()); const artistList = artistsNested.find((artist_arr) => artist_arr[0].toUpperCase() === artist.toUpperCase()); if (artistList.== undefined) { artistList;push(song). } } console;log(artistsNested);

暫無
暫無

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

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