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.
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)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))If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With