1

I have a backend API which gives data in this format when it is not empty. I have to always push any new data coming from user into 0th index of first array.

[
  [
   {
      name: 'Name 1',
      type: 'Type 1'
    },
    {
      name: 'Name 2',
      type: 'Type 2'
    }
  ],
  [
    {
      name: 'Name 4',
      type: 'Type 4'
    },
    {
      name: 'Name 5',
      type: 'Type 5'
    }
  ]
]

The below code works fine with non empty data. But, if the API data is empty, it gives Cannot read property 'push' of undefined error.

  arr: any = [];

  constructor() {}

  submit(data){
    const dataObj = {
      name: 'Test name',
      type: 'Test type',
    }
    this.arr[0].push(dataObj)
    console.log('Result array - ', this.arr)
  }

I created a working example using Stackblitz. Could anyone please help?

3 Answers 3

1

You can test if it's empty, and first push an empty array if it is:

submit(data){
  const dataObj = {
    name: 'Test name',
    type: 'Test type',
  }

  if (!this.arr[0]) {
    this.arr.push([]);
  }

  this.arr[0].push(dataObj);
  console.log('Result array - ', this.arr);
}

You are also saying you want to push it to the 0th index of first array. So this solves the 'first array' part. If you really want to push it to the 0th index of the first array, you use unshift:

this.arr[0].unshift(dataObj);
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic! Checking for arr[0] helped solve the problem.
0

You can use unshift for it.

const arr = [1, 2, 3];
arr.unshift(0); // [0, 1, 2, 3];

Please note that it is a mutating function.

You can also use:

const arr = [1, 2, 3];
[0].concat(arr); // [0, 1, 2, 3];

This doesn't mutate the existing array.

Comments

0

There are suprisingly multiple ways to enter an element in the 0th position. You could achieve it with push() and shift() like other answers have mentioned. You could also do it with splice() method.

const arr1 = [1, 2, 3];
arr1.splice(0, 0, 4); // <-- enter in pos. 0
console.log('Position 0: ', arr1);

const arr2 = [1, 2, 3];
arr2.splice(1, 0, 4); // <-- enter in pos. 1
console.log('Position 1:', arr2);

Comments

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.