Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort part of Array based on another array in JS

I've seen similar questions. But I'm trying to do a partial sort of an array based on values from another array.

Here is what I'm looking for:

let array = [
  {
    name: "Foo",
    values: [a, b, c, d]
  },
  {
    name: "Bar",
    values: [x, y]
  },
  {
    name: "FooBar",
    values: [k, l, m]
  },
  {
    name: "BarBar",
    values: [m, n]
  }
]

and

let sort = ["BarBar", "Bar"]

and the desired output is:

let desiredOutput = [
  {
    name: "BarBar",
    values: [m, n]
  },
  {
    name: "Bar",
    values: [x, y]
  },
  {
    name: "Foo",
    values: [a, b, c, d]
  },
  {
    name: "FooBar",
    values: [k, l, m]
  }
]

Array is sorted based on only two values and every other elements follow the same order.

I'm wondering if it is possible to achieve this.

like image 287
user1012181 Avatar asked Oct 29 '25 00:10

user1012181


2 Answers

You could use sort method to first sort by condition if element exists in array and then also by index if it does exist.

let array = [{name: "Foo",},{name: "Bar",},{name: "FooBar",},{name: "BarBar",}]
let sort = ["BarBar", "Bar"]

array.sort((a, b) => {
  let iA = sort.indexOf(a.name);
  let iB = sort.indexOf(b.name);
  return ((iB != -1) - (iA != -1)) || iA - iB
})

console.log(array)
like image 121
Nenad Vracar Avatar answered Oct 30 '25 13:10

Nenad Vracar


let array = [
  {
    name: "Foo",
    values: "[a, b, c, d]"
  },
  {
    name: "Bar",
    values: "[x, y]"
  },
  {
    name: "FooBar",
    values: "[k, l, m]"
  },
  {
    name: "BarBar",
    values: "[m, n]"
  }
]

let sort = ["BarBar", "Bar"]

const sortWithAnotherArray=(arr,sortBy)=>{
  let begin =sortBy.map(e=>arr.filter(v=>v.name===e))
  let end = arr.filter(e=>sortBy.includes(e.name))
  return begin +end
}
console.log(sortWithAnotherArray(array,sort))
like image 30
Naor Tedgi Avatar answered Oct 30 '25 13:10

Naor Tedgi