Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

reactjs - react native - sorting array for an selected item

I am just experiencing a slight issue with an array as I have created a JSON list of podcast episodes, and when you click one it will play that podcast episode on the next screen.

I pass both the selected episode + the whole episodes array onto the player screen. Like so

const { episodes, episode } = route.params;

Then I add them both to an array, and then loop through the array and remove the duplicate element of the array.

    var updated_array = [episode, ...episodes];

    updated_array.forEach(obj => {
      // check if their are any duplicate ids
      // if so, push only one to the newArray
      if (!newArray.some(o => o.id === obj.id)) {
        newArray.push({ ...obj })
        //newArray.sort((a, b) => (a.id > b.id) ? 1 : -1);
        console.log(newArray);
      }
    });

Which then I add the array to the TrackPlayer

await TrackPlayer.add([...newArray]);

If there is a cleaner way of doing this please let me know but at the moment if I select an episode which has the id of 4 for example, it'll mess up structure of the array, as when I go the next element, it will not be element 5, it will be element 1.

So all I want to do is have the newArray be sorted so whatever the selected index is, the array will sort it so the flow is not messed up when I am toggling through the podcast episodes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...