Search code examples
javascripttypescriptjavascript-objects

JavaScript array unshift if values present in other array


I've two array of objects one selected and other general data which we're displaying

General data for display

const arr = [
  {
    id: "1",
    name: "Skoda - Auto"
  },
  {
    id: "2",
    name: "BMW - Auto"
  },
  {
    id: "3",
    name: "Mustang"
  },
  {
    id: "2",
    name: "Ferrari"
  },
  {
    id: "1",
    name: "Ford"
  }
];
selectedValues 

const selectedArr = [
  {
    id: "1",
    name: "something - 1"
  },
 {
    id: "3",
    name: "something - 1"
  }
]

I want to sort the general data for display based on this selected array. so basically I want to match the id from selectedArr check if this id is present in general array if yes the shuffle the general array so that selected values are at the top of the array O/P

const arr = [
  {
    id: "1",
    name: "Skoda - Auto"
  },
  {
    id: "1",
    name: "Ford"
  },
  {
    id: "3",
    name: "Mustang"
  },
  {
    id: "2",
    name: "BMW - Auto"
  },
  {
    id: "2",
    name: "Ferrari"
  },
];

There are multiple values with same id, I need to unshift those values at the top if it exisits in selected Array. I'm not sure how to achieve such output, hence need some help on this


Solution

  • This can be achieved by indexing your sorting array into a map that gives an index for a given id:

    const selectedArr = [
        {
            id: "1",
            name: "something - 1"
        },
        {
            id: "3",
            name: "something - 1"
        }
    ]
    
    const sortMap = new Map(selectedArr.map(({ id }, idx) => [id, idx]));
    

    then using this in the standard sort function (here, I'm taking a copy of the array with [...arr] because sort is in-place and I'm a big fan of avoiding mutation). We give items that are not present in the sortMap a sufficiently large index that they'll go to the bottom of the list...

    const sortedArray = [...arr].sort(
        (a, b) => (sortMap.get(a.id) ?? 10000000) - (sortMap.get(b.id) ?? 10000000)
    );
    

    Playground Link

    const arr = [{
        id: "1",
        name: "Skoda - Auto"
      },
      {
        id: "2",
        name: "BMW - Auto"
      },
      {
        id: "3",
        name: "Mustang"
      },
      {
        id: "2",
        name: "Ferrari"
      },
      {
        id: "1",
        name: "Ford"
      }
    ];
    
    const selectedArr = [{
        id: "1",
        name: "something - 1"
      },
      {
        id: "3",
        name: "something - 1"
      }
    ]
    
    const sortMap = new Map(selectedArr.map(({
      id
    }, idx) => [id, idx]));
    
    const sortedArray = [...arr].sort((a, b) => (sortMap.get(a.id) ?? 10000000) - (sortMap.get(b.id) ?? 10000000));
    
    console.log(sortedArray)