skip to Main Content

Hey so i have one array with data like this

arr1 = [
{mood: "good", name: "Jake"},
{mood: "good", name: "Jill"},
{mood: "good", name: "Jack"}
]

and another array

arr2 = [
{number: 2, name: "Jake"},
{number: 1, name: "Jill"},
{number: 3, name: "Jack"}
]

I was looking to sort array one using the number from array 2. So, basically I would need to use a filter to match the name from arr1 to arr2 and then get the number from the resulting array and sort.

How can I get this done ?

arr1.sort((a: any, b: any) => arr1.filter((item: { name: string; }) => item.name == arr2[i].name));

I am totally lost, so much so, I may not have asked a proper question !

2

Answers


  1. You can create a lookup function to find the number, like this:

    const arr1 = [{"mood":"good","name":"Jake"},{"mood":"good","name":"Jill"},{"mood":"good","name":"Jack"}]
    const arr2 = [{"number":2,"name":"Jake"},{"number":1,"name":"Jill"},{"number":3,"name":"Jack"}]
    
    const f = ({name: a}) => arr2.find(({name: b}) => a === b).number
    
    arr1.sort((a, b) => f(a) - f(b))
    
    console.log(arr1)

    If you want to improve performance, you can use a cache, like this:

    const arr1 = [{"mood":"good","name":"Jake"},{"mood":"good","name":"Jill"},{"mood":"good","name":"Jack"}]
    const arr2 = [{"number":2,"name":"Jake"},{"number":1,"name":"Jill"},{"number":3,"name":"Jack"}]
    
    const cache = {}
    const f = ({name: a}) => cache[a] ??= arr2.find(({name: b}) => a===b).number
    
    arr1.sort((a, b) => f(a) - f(b))
    
    console.log(arr1)
    Login or Signup to reply.
  2. You could simply use an object for the order of name and take the value for sorting.

    const
        arr1 = [{ mood: "good", name: "Jake" }, { mood: "good", name: "Jill" }, { mood: "good", name: "Jack" }],
        arr2 = [{ number: 2, name: "Jake" }, { number: 1, name: "Jill" }, { number: 3, name: "Jack" }],
        order = Object.fromEntries(arr2.map(({ name, number }) => [name, number]));
    
    arr1.sort((a, b) => order[a.name] - order[b.name]);
    
    console.log(arr1);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search