Skip to content
Advertisement

How to put index as recognizing same number of sorted array in JavaScript?

I’m dealing with immutable objects.

I sort data by thisweekNumber as you can see below.

JavaScript

For exmaple,

JavaScript

I sort them B -> D -> E -> A -> C

So I want to put Index to them in this order:

JavaScript

BUT here, I want to recognize same thisweekNumber of D and E.

Since they both have 4.

So Index will be like above.

How can I make this array in JavaScript?

Advertisement

Answer

The simplest thing I can think of is to do it after sorting, with a simple loop:

JavaScript

JavaScript
JavaScript

Note the use of optional chaining in the if.


In a comment you’ve said:

thanks i understand the concept ! but my object seems not extensible in the process ‘current.index = index’. erorr says : cannot add property index, object is not extensible.

You didn’t mention that in the question. If you’re dealing with immutable objects, you’ll need to create new objects (probably in a new array). Creating the objects is typically done using spread syntax:

JavaScript

You can easily do that in the loop above, pushing to an in-scope array:

JavaScript
JavaScript

…or via map:

JavaScript
JavaScript

The map version is probably more idiomatic.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement