0

This is my code:

var newArray = [];
newArray[3] = "Three"
newArray[1] = "One"
newArray[2] = "Two"

Result of this array is:

1: One
2: Two
3: Three

But I want to get result like this (sort by append):

3: Three
1: One
2: Two

Note: I don't want to lose the keys.

2
  • Show the JavaScript that you used as a minimal reproducible example. The code you have so far means nothing because it doesn't even correctly represent correct syntax, so it's impossible to guess exactly how you got those pseudo-code results in the first place. Commented Apr 7, 2022 at 6:23
  • 1
    You can normally push the data sequentially into the array using push(), but if you want the data to be pushed sequentially and have the indexing different from the way you pushed it is not possible . Commented Apr 7, 2022 at 6:24

1 Answer 1

1

you should push it sorted inside array, then it will print it in the order you added it.

newArray.push("Three")
newArray.push("One")
newArray.push("Two")

then you can do 1 thing key your assigning code, other then this array create one seprate array for only keys but that keys should be sorted in array like

keysArray.push(3)
keysArray.push(1)
keysArray.push(2)

keysArray.map(myKey=>{
  console.log(newArray[myKey])
})
Sign up to request clarification or add additional context in comments.

2 Comments

But I want to use KEYs. I don't want to lose the keys.
please check updated solution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.