4

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.

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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))

Comments

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.