1

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 },
]
7
  • So if you want to move to position 1, then whatever IS at position 1 gets to be its position-1? Commented Nov 3, 2022 at 14:02
  • Why not just have two arrays? One for social and one for platform? Commented Nov 3, 2022 at 14:04
  • There are a number of different structures in which you could store this kind of data that would make this type of operation less cumbersome, are you open to changing the structure of the data? Commented Nov 3, 2022 at 14:07
  • @mplungjan actually, it should be its position + 1... Consider this like drag&drop... If you move something up, everything else below that position should be moved below. Commented Nov 3, 2022 at 15:00
  • @HereticMonkey what do you have in mind? Currently, I store this data in mongodb, and on frontend its drag&drop.. And on frontend its hardcoded that android&ios have the same box... Commented Nov 3, 2022 at 15:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.