PDA

View Full Version : Deleting specific elements of an array



Sriramdasty
Jun 20th, 2007, 08:44 AM
Hey guys, how to delete specific elements of an array element in JS.

For example, if i have an array result[] with vaules PASS/FAIL and if i set a conditin like

if(result[i]=="FAIL")
{
CODE
}

in the code part, i want to delete the specific element of array containing FAIL values and shift the rest such that the array should contain all PASS.

I think, im confusing you......Ok...I will make everything clear, For example, i design a script to get input of marks and students name.
I put the total and if the total is lessthan a certain value, i declare the result[] as "FAIL" and i want to eliminate such students who have got "FAIL" from the array list during the output.
What should i do. I want to delete the array element "FAIL" thro'out the array and to fill those spaces, i want to contract the array by making the next element to occupy that place. And correspondingly, i will also, move the student name and total arrays.

Thanks in advance!

LFCFan
Jun 20th, 2007, 11:46 AM
Hi,

I think this should work:



if(result[i] == "FAIL")
{
delete result[i]
}


Cheers
Joe

Philip M
Jun 20th, 2007, 12:46 PM
You need to set up another array containing just the pass details.

var result = new Array(); // presumably an array containing all the marks
var passonly= new Array();
var count = 1;

for (i = 1; i<= result.length; i++) {
if (arr.[i] = "PASS") { // presumably PASS is a number equivalent to the pass mark, e.g. >=50
passonly[count] = result[i];
count++;
}
}

Naturally this will have to be refined to include the name of the student and whatever.

Mr J
Jun 20th, 2007, 01:58 PM
Another possibility

arr=["pass","fail","pass","fail"]

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

alert(arr)

LFCFan
Jun 20th, 2007, 02:12 PM
Another possibility

arr=["pass","fail","pass","fail"]

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

alert(arr)


Thought splice() was Netscape?

Joe

Philip M
Jun 20th, 2007, 02:39 PM
[QUOTE=LFCFan;578645
Thought splice() was Netscape?

Joe[/QUOTE]

MSIE5.5+ supports splice(). Doubt if many people use IE5 any more.

Sriramdasty
Jun 20th, 2007, 08:21 PM
He guys....Really cool ideas..

I expermiented all of the ideas and everything worked!!!

Thanks a lot..

I find splice() as an easy option!!
Thank you.!!

Mr J
Jun 20th, 2007, 09:42 PM
splice appears to work ok in Mozilla, Firefox, netscape8, Opera, and IE6,7