0

I am searching any times, but I am not finding any solution exactly what I want. My question is How can I sort array with another array that defined the array order.

Suppose-

const array1 = [
    {
        name: "1"
    },
    {
        name: "2"
    },
    {
        name: "3"
    }
]

const array2 = ["3", "1"]

I need to sort array1 by following

const array = [
    {
        name: "3"
    },
    {
        name: "1"
    },
    {
        name: "2"
    }
]

Here, we can see array2 values are now top of array1. I want this function.

I already tried, but gives wrong result-

const sortMarkets = (array: ArrayTypes[], sortArray: string[]) => {
  return [...array].sort(
    (a, b) => sortArray.indexOf(a.name) - sortArray.indexOf(b.name)
  )
}

console.log(sortMarkets(array, ag));

It gives me-

[{
  "name": "2"
}, {
  "name": "1"
}, {
  "name": "3"
}] 

Please help me.

0

2 Answers 2

0

You need to get another value for unknow items. In this case, a large value moves the item to the end.

const
    array = [{ name: "1" }, { name: "2" }, { name: "3" }],
    ag = ["3", "1"],
    sortMarkets = (array, sortArray) => {
        const getOrder = name => (sortArray.indexOf(name) + 1) || Number.MAX_VALUE;
        return [...array].sort((a, b) => getOrder(a.name) - getOrder(b.name));
    };

console.log(sortMarkets(array, ag));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

-1

Comparing the .indexOf with the value the other array isn't enough because there are two criteria to sort by - one, for elements in the other array to come on top of the others, and two, for those top elements to be sorted according to their position in the other array. Add another check first to see whether the items being compared should come in different sections (on the top or the bottom).

const array1 = [
    {
        name: "1"
    },
    {
        name: "2"
    },
    {
        name: "3"
    }
];
const array2 = ["3", "1"];
array1.sort((a, b) =>
  (array2.includes(b.name) - array2.includes(a.name))
  || (array2.indexOf(a.name) - array2.indexOf(b.name))
);
console.log(array1);

To make TypeScript happy, cast the booleans to numbers before subtracting.

(Number(array2.includes(b.name)) - Number(array2.includes(a.name)))

3 Comments

Working but gives me typescript error
Includes gives me true of false. then how, it done a arithmetic operations
Cast the booleans to numbers before subtracting

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.