0

I have an array of objects like this. The result is shown by console.log()

(5) [{…}, {…}, {…}, {…}, {…}]
0:
  name:"SOMEVALUE"
  partyDetails"SOMEVALUE"
  __proto__:Object
1:
  name: "SOMEVALUE"
  partyDetails: "SOMEVALUE"
  __proto__:Object
2:
  name:"SOMEVALUE"
  partyDetails: "SOMEVALUE"
  __proto__: Object
3:
  name:"SOMEVALUE"
  partyDetails:"SOMEVALUE"
  __proto__: Object
4:
  name:"SOMEVALUE"
  partyDetails: "SOMEVALUE"
  __proto__:Object
length:5
__proto__:Array(0)

After deleting from the object by this command,

delete  $scope.excelInfo.columnDefs[3];
delete  $scope.excelInfo.columnDefs[4];

I get this on console.log

(5) [{…}, {…}, {…}, empty × 2]
 0:
   name:"SOMEVALUE"
   partyDetails:"SOMEVALUE"
   __proto__:Object
 1:
   name:"SOMEVALUE"
   partyDetails:"SOMEVALUE"
   __proto__:Object
 2:
   name:"SOMEVALUE"
   partyDetails:"SOMEVALUE"
   __proto__:Object
 length:5
 __proto__:Array(0) 

How you see there are empty × 2 in the last array of objects, after delete.

What should I do to remove this 2 empty rows?

This 2 empty row make my data wrong in the view.

Is there any good solution?

I do not want to check if data equal to null.

Thanks a lot

georgeawg
  • 46,994
  • 13
  • 63
  • 85
Aram Grigoryan
  • 688
  • 1
  • 6
  • 23
  • 1
    just take a look at :https://stackoverflow.com/questions/5767325/how-do-i-remove-a-particular-element-from-an-array-in-javascript as – Afshin Amiri Jun 05 '18 at 09:27

3 Answers3

2

You can use splice() to remove last two object without setting undefined as it does when you use delete

var arr = [
  {
    name:"SOMEVALUE1"
  },
  {
    name:"SOMEVALUE2"
  },  
  {
    name:"SOMEVALUE3"
  },  
  {
    name:"SOMEVALUE4"
  },  
  {
    name:"SOMEVALUE5"
  }
];

arr.splice(3,2)
console.log(arr);

Or using delete you need to also filter the defined objects only,

var arr = [
  {
    name:"SOMEVALUE1"
  },
  {
    name:"SOMEVALUE2"
  },  
  {
    name:"SOMEVALUE3"
  },  
  {
    name:"SOMEVALUE4"
  },  
  {
    name:"SOMEVALUE5"
  }
];

delete arr[3];
delete arr[4];
var res = arr.filter(item => item);
console.log(res);
Ankit Agarwal
  • 28,439
  • 5
  • 29
  • 55
1

Use Array.splice

$scope.excelInfo.columnDefs.splice(3,2)

e.g.

var arr = [1,2,3,4,5];
arr.splice(3,2);
console.log(arr);
Nikhil Aggarwal
  • 26,884
  • 3
  • 37
  • 53
1

Array.prototype.splice() the array instead of using delete.

$scope.excelInfo.columnDefs.splice(3, 2);
//                                 ^  ^
//                                 |  |
//                                 |  Number of elements to remove
//                                 Index at which to start removing

splice() modifies the array in place, so there is not need to reassign it.

Robby Cornelissen
  • 72,308
  • 17
  • 104
  • 121