Reputation: 3543
I have a 2D array named extraRank
which holds other users arrays named userA, userB, userC and userD whenever I push them into it:
// users arrays:
userA = ["Sara Ree",18, "Doctor", "441", "31"];
userB = ["Marry",18, "Nurse", "41", "1"];
userC = ["John Doe",18, "Woker", "21", "31"];
userD = ["Alex Morph",18, "Musisian", "81", "51"];
// users arrays may be pushed to this array
let extraRank = [];
what I want is an efficient way to do this:
first, check which users arrays exist in extraRank
.
then if for example, userA exist do this:
if extraRank.indexOf(userA) == 0
then assign userA_Index = 10;
if extraRank.indexOf(userA) == 1
then assign userA_Index = 9;
if extraRank.indexOf(userA) == 2
then assign userA_Index = 8;
if extraRank.indexOf(userA) == 3
then assign userA_Index = 7;
I know one way is to this using if statements for each user, but I'm wondering if there is a more efficient way to do it...
Upvotes: 1
Views: 47
Reputation: 845
I don't totally understand your requierement, but would a simple substraction do the trick ?
userA_Index = 10 - extraRank.indexOf(userA)
But I'm not sure of what you want to achieve here.
Edit: You say that you want to optimize for execution time. This will be more efficient that a bunch of if. However, I don't think even 10 if
statements are going to be noticeable.
How slow is your code now ? How many user
do you have ?
You migth have other place to optimise first, but it is hard to say without a larger view of your app.
Upvotes: 1
Reputation: 10176
If the assignment is linear, as suggested by your example, you can do a simple subtraction:
userA_index = 10 - extraRank.indexOf(userA)
If it is more complex, you can create a map object that connects the index to the result, such as:
const mapIndexToOutput = {
0: 10,
1: 9,
2: 8,
3: 7,
...
}
userA_index = mapIndexToOutput[extraRank.indexOf(userA)]
Upvotes: 2