Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splice row from array by value

I want splice the line with value = 3

[3,"John", 90909090]

data.json

{
"headers":[[
{"text":"Code","class":"Code"},
{"text":"Code","class":"Code"}
]],
"rows":[
[0,"Peter", 51123123],
[3,"John", 90909090],
[5,"Mary",51123123]
],
"config":[[0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],
"other":[[13,0]]
}

I try this:

var size = data.rows.length; // number of rows

var del = 3 // Value of ID to be deleted          

for (i = 0; i < size; i++) {  

var id = data.rows[i][0];                  

    if(del==id){  // if del = id -> splice                                         

       data.rows.splice(i,1);

    }

}

Results:

Only splice or only loop this code works.

But, with both show this error:

Uncaught TypeError: Cannot read property '0' of undefined(…)

It occurs in "data.rows[i][0]"

like image 326
Gurigraphics Avatar asked Nov 16 '16 12:11

Gurigraphics


People also ask

How do you splice an element from an array?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.

Can you splice an array?

The splice() method is used to add or remove elements of an existing array and the return value will be the removed items from the array. If nothing was removed from the array, then the return value will just be an empty array. Here is the basic syntax. In this example, we have an array of food items.

What is the use of splice () method returns a section of an array?

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

Why is splice not working on array?

It's not working because you are removing items from the array while looping through the keys. When you remove an item, it will rearrange the other items depending on how the array is implemented internally, and you end up with a loop that doesn't iterate over the keys that you expect.


1 Answers

instead of using a for loop, id use the array filter function:

data.rows = data.rows.filter(function(row){
    return row[0] !== del;
});
like image 184
hello_world Avatar answered Nov 14 '22 22:11

hello_world