Home Ask Login Register

Developers Planet

Your answer is one click away!

HEYHEY February 2016

js slicing even number in array

So, I have object which I am splitting, but it is leaving a comma in between.

I thought I would use slice to only select the even number position to ignore the comma:

alert(sample); // first_name|^&|last_name|^&|

   var test = sample.split('|^&|');

Giving: first_name,last_name

However, the comma is counted as an array and giving me a headache.

So, I thought I would use slice to select only the [0], [2], [4] and so on, thus ignoring the comma.

How do I select only the even number? (var test = sample.split(',').slice(?);)?


Paolo February 2016

You don't have any commas in test elements

sample = 'first_name|^&|last_name|^&|';

test = sample.split('|^&|');

alert( test[ 0 ] ); // first_name

alert( test[ 1 ] ); // last_name

The only issue you may have is that as there is a trailing separator |^&| in sample you also have an empty element at the end of the array...

alert( test[ 2 ] ); // (empty string)

...that you may get rid of with just

test.pop(); // removes the last item of the array

Jtaks February 2016

Split takes a string and splits into an array. If you use sample.split('|^&|'), it should split on all occurrences of '|^&|'.

var sample = "foo|^&|bar";
var test = sample.split('|^&|');
// Output: ["foo", "bar"]
// Access: test[0] === "foo", etc.

If you need to retrieve every even element of the array, slice might not be the best bet. Try using something like:

var i;
for(i = 0; i < test.length; i++) {
  if ((i % 2) === 0)
    // do something with the element here

Post Status

Asked in February 2016
Viewed 2,979 times
Voted 11
Answered 2 times


Leave an answer

Quote of the day: live life