0

Is there any better way to push something to undefined index in array instead of this:

// Just an example

let array = [];
let indexInArray = 0;
let data = "data";

// This throws error
// array[indexInArray].push(data);

for(let i = 0; i <= 1; i++) {
    if(array[indexInArray] == undefined) {
        array[indexInArray] = [data];
    } else {
       // This throws error if i = 0
       array[indexInArray].push(data);
    }
}

// array = [["data", "data"]];

I am looking for pushing to undefined index in array.

So I need to create array in index and then do push().

1
  • 1
    What do you want to achieve with that? Commented Aug 30, 2019 at 20:05

2 Answers 2

2

I think what you're looking for is this:

const array = [];

array[42] ='hello';

You can set a value at a specific index in an array simply by assigning to that value.

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

6 Comments

I am sorry. I edited my post. I need to push to array in index. I want to do this before always checking if array in index is undefined or not.
It's can't push anything in that array, In Javascript array [] and objects {} both typeof is objects, So here you assign a key value pair array[42] ='hello' into an array.
Even you can do this array[-1] = '-1'
@NeelRathod I am looking for something like this. But I need to do this on index in array not in array.
@JohnDoe It seems like you want to convert array elements of undefined to it's index. Ex. [1,2, undefined] => [1,2,2]
|
0

You don't need to use push for that, you just need to do this arr[index] = data

const array = [1, 2, undefined];
const data = 'Neel';
array[3] = data;
array[10] = data;
console.log(array); 

Note: If you assign a value on above max index then a value of between index will be undefined, Check above snippet for index 10

6 Comments

Sorry for misunderstanding. Look at my post. This is not my problem.
I know that. But I want to push a few data to array[index]. I need array in array[index] and push into it.
Please put your expect output
Done. I've already have not idea how to explain it better. Thanks for your time!
@JohnDoe Happy to help..Anything wrong with this answer? Please comment on, upvote or indeed accept answers. –
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.