Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of the javascript array does not change after deleting the element from it

I am trying to copy one array values into another, but without breaking the links that is associated with this array other words i can not just assign the new array to this value, thats why i cannot use methods like slice() or concat(). Here is the code of the function that does the thing:

 self.updateBreadcrumbs = function (newBreadcrumbs) {
            var old_length = self.breadcrumbs.length;
            var new_length =newBreadcrumbs.length;
            var j = new_length > old_length ? new_length: old_length;

            for (var i = 0; i < j; i++) {
                if(old_length < i+1){
                    self.breadcrumbs.push(newBreadcrumbs[i]);
                    continue;
                }
                if(new_length < i+1){
                    delete self.breadcrumbs[i];
                    continue;
                }
                if (self.breadcrumbs[i].title !== newBreadcrumbs[i].title) {
                    self.breadcrumbs[i] = newBreadcrumbs[i];
                }

            }
        }

My problem is that length of the array does not change when i delete something from the array.

P.S If you know any easier way to do this i am totally open for propositions.

like image 218
Dmitrij Kostyushko Avatar asked Feb 09 '16 16:02

Dmitrij Kostyushko


1 Answers

Length of an Array can never change by deleting elements in it.

However It can be altered with splice eg.

var arr=[1,2,3,4,5]; //length 5
arr.splice(0,1); //length 4

Unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory. delete is only effective on an object's properties. It has no effect on array length

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

More about Splice

like image 138
Vicky Gonsalves Avatar answered Sep 22 '22 14:09

Vicky Gonsalves