3

I have a remove[] array which has all the index positions of all the element with 0 in the data array (as below).

data array:

Retail,1,Utilities,1,Food & Restaurant,3,No Data,4,Construction,0,Non-profit,1,Financial Services,12,Technology,2,Law,3,Religion,3,Retired,2,Insurance,0,Real Estate,2,Audit,3,Business Organizations,3,Media & Marketing,0,Education,3,Transportation,0,Manufacturing,0,Entertainment & Sports,0,Architecture & Engineering,0,Cultural Institutions,0,Government,0,Banking,0,Health Care,0,Business Services,0

my javascript

   var remove =  [];          
    $.each(options.series[0].data, function(index, item) {
    if (options.series[0].data[index][1] == 0)
    {                    
        //options.series[0].data.splice(index,1);  
        remove[index] = index;                                      

    }

    for (i=0; i<=remove.length; i++)
    {
    //alert(remove);                
    if (remove[i] != undefined)
        options.series[0].data.splice(remove[i],1);

    }   

data array after splice(). A lot of elements with 0 are still there.

Retail,1,Utilities,1,Food & Restaurant,3,No Data,4,Non-profit,1,Financial Services,12,Technology,2,Law,3,Religion,3,Retired,2,Insurance,0,Audit,3,Business Organizations,3,Media & Marketing,0,Education,3,Manufacturing,0,Entertainment & Sports,0,Cultural Institutions,0,Banking,0,Business Services,0

if i changed the splice to include replacement element

options.series[0].data.splice(remove[i],1,'removed');

All 0 elements are removed from the data array. huh?

Retail,1,Utilities,1,Food & Restaurant,3,No Data,4,removed,Non-profit,1,Financial Services,12,Technology,2,Law,3,Religion,3,Retired,2,removed,Real Estate,2,Audit,3,Business Organizations,3,removed,Education,3,removed,removed,removed,removed,removed,removed,removed,removed,removed

How do I remove all the 0 elements in my data array?

imObjCSwifting
  • 743
  • 1
  • 12
  • 34
  • possible duplicate of [Delete from array in javascript](http://stackoverflow.com/questions/9362412/delete-from-array-in-javascript) – Rob W Mar 12 '12 at 22:49
  • It looks like the members of the array should be strings. You haven't quoted them so they are interpreted as identifiers, you should be getting errors - unless you aren't posting the real code. – RobG Mar 12 '12 at 22:50

6 Answers6

16

Every time you remove one, you're making any further cached indices obsolete because the array from that point forward is reindexed.

As a result, you're removing the wrong items after the first.

You should iterate the remove array in reverse instead.

var i = remove.length;
while (i--) {
    if (remove[i] != undefined)
        options.series[0].data.splice(remove[i],1);
}   

Additionally, you can improve the performance and get rid of the undefined test if you simply .push() each index into the remove array...

remove.push(index);
  • 1
    It should work forwards too **provided** there is a one–for–one swap, since the inserted element replaces the removed one the indexes are not affected. Otherwise, yes, it should be done backwards. – RobG Mar 12 '12 at 22:53
  • @RobG: The inserted element is part of the working code. OP stated that doing an insertion solves the issue, but an insertion isn't wanted. EDIT: Saw your update... yes, provided there's an insertion, it will work. –  Mar 12 '12 at 22:56
  • Excellent. That works. I was also wondering how to get rid of the undefined values in remove[]. You read my mind and answered :). – imObjCSwifting Mar 13 '12 at 00:06
  • @EverydayImSeeSharping: Glad it worked. :) FYI, unless you have another use for the `remove` Array, you could always just reverse iterate the `options.series[0].data` Array directly, and do the `splice()` right there. –  Mar 13 '12 at 00:25
  • 1
    @amNot—a few distractions when typing. :-) – RobG Mar 13 '12 at 01:02
1

My problem was that splice was removing the wrong element from the array. I saw the answer with the while loop but the solution that I made is :

var index = jQuery.inArray(element, arr);
arr.splice(index,1);
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
user1
  • 1,035
  • 1
  • 9
  • 17
0

I think you can do it pretty fast this way:

var dataArr = ["Retail",1,"Utilities",1,"Food & Restaurant",3,"No Data",4,"Construction",0,"Non-profit",1,"Financial Services",12,"Technology",2,"Law",3,"Religion",3,"Retired",2,"Insurance",0,"Real Estate",2,"Audit",3,"Business Organizations",3,"Media & Marketing",0,"Education",3,"Transportation",0,"Manufacturing",0,"Entertainment & Sports",0,"Architecture & Engineering",0,"Cultural Institutions",0,"Government",0,"Banking",0,"Health Care",0,"Business Services",0];

var item = 0; // value of the item to remove

while (dataArr.indexOf(item) > -1) {
 dataArr.splice(dataArr.indexOf(item), 1);
}

console.log(dataArr);
Izaias
  • 389
  • 3
  • 15
0

I use a library called DevBox.Linq.JS

It basically adds Linq type functionality to Javascript Arrays. For example, it adds "Remove":

   Array.prototype.Remove = function (condition) {
    if (condition == undefined) {
        console.error('Informe a expressão para executar a tarefa.')
        return;
    }

    for (var i = 0 ; i < this.length ; i++) {
        if (condition(this[i]))
            this.splice(i, 1);
    }
}

This way you can use it with a lambda like this:

myArray.remove(i=>i=="valueToDelete");

Hope it helps, It already has all the functionality so you don't have to deal with that pesky splice.

0

If you look at your original array and the first result array, you'll notice that non-0 elements ARE being removed. The problem from what I can tell is that your array remove is looking for indices that have since been shifted over one to the left upon the removal of previous ones. You will need to add a correcting adjustment for this in your final for loop, or approach this another way.

cmw
  • 855
  • 7
  • 17
0

If you want to remove all the elements from an array, it's better don't use splice but length:

options.series[0].data.length = 0;

See: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/length

Update:

I misunderstood the question. In your case I will probably filter out the elements that are zero, instead of makes two loop (one for collect them, and one for remove them). So, something like:

function isNotZero(item) {return item[1] !== 0}

var filtered = options.series[0].data.filter(isNotZero);

options.series[0].data = filtered;

See: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter

If the browser you want to support doesn't implement ES5, I will suggest to you to use a shim for all the es5 methods (in that page there is one for filter), or library like underscore

ZER0
  • 24,846
  • 5
  • 51
  • 54
  • Not all elements are being removed. OP is building a list of the indices of elements that have the value `0`, and only removing those. –  Mar 12 '12 at 23:30