I have the next array:
const links = [
{ link: "google", sort: 0 },
{ link: "facebook", sort: 1 },
{ link: "ios", sort: 2 },
{ link: "android", sort: 3 },
{ link: "twitter", sort: 4 },
]
First thing I need is to change positions of elements. I did this with:
const linkName = "twitter";
const sort = 1;
const currentIndex = links.findIndex((e) => e.link == linkName);
links.splice(sort, 0, links.splice(currentIndex, 1)[0]);
links.map((e, i) => {
e.sort = i;
});
/* modified array:
[
{ link: 'google', sort: 0 },
{ link: 'twitter', sort: 1 },
{ link: 'facebook', sort: 2 },
{ link: 'ios', sort: 3 },
{ link: 'android', sort: 4 }
]
*/
After this, twitter should be moved to index 1, and everything else should move one sort.
What I need is to keep "android" and "ios" in some sort of group. So those 2 would have the same sort. I want to end up with next array:
[
{ link: "google", sort: 0 },
{ link: "facebook", sort: 1 },
{ link: "ios", sort: 2 },
{ link: "android", sort: 2 },
{ link: "twitter", sort: 3 },
]
And for example, if I receive I want to move "ios" OR "android" to 0 index, it should look like this:
[
{ link: "ios", sort: 0 },
{ link: "android", sort: 0 },
{ link: "google", sort: 1 },
{ link: "facebook", sort: 2 },
{ link: "twitter", sort: 3 },
]
And if I want to move them to index 1, then it should look like this:
[
{ link: "google", sort: 0 },
{ link: "ios", sort: 1 },
{ link: "android", sort: 1 },
{ link: "facebook", sort: 2 },
{ link: "twitter", sort: 3 },
]