1

I have an array like :

var arr = [["series0","44","24",56,12 ]]

How to trim(remove) the first element, here it is "series0" ? I already tried most predefined js function but could not find solution. Thanks all for great answers.What would be best way to sort the array, i already tried for:

.sort(function(a, b){return a-b})

and also:

arr.sort(function(a,b) {
  if (isNaN(a) || isNaN(b)) {
    return a > b ? 1 : -1;
  }
  return a - b;
});

I need the sort result should return like arr=[["series0","12","24","44","56"]] Rather i am getting [["12","24","44","56","series0"]]

7
  • 3
    arr[0] = arr[0].splice(0, 1); Commented Feb 25, 2016 at 9:25
  • check out my answer. Commented Feb 25, 2016 at 9:27
  • 1
    @Tushar how about arr[0].shift() Commented Feb 25, 2016 at 9:28
  • 1
    arr[0].shift() is simpler Commented Feb 25, 2016 at 9:28
  • @Tushar, no assignment necessary, the splice returns the spliced part/s. Commented Feb 25, 2016 at 9:37

5 Answers 5

3

The shift method removes the first element, you can call it on the first element of your array:

arr[0].shift()
Sign up to request clarification or add additional context in comments.

Comments

1

Use splice(), by changing second parameter you can remove more than one elements

var arr = [
  ["series0", "44", "54", 56]
];
arr[0].splice(0, 1);

document.write(JSON.stringify(arr));

EDIT : In case if you just want to remove single element then shift() will be best solution

var arr = [
  ["series0", "44", "54", 56]
];
arr[0].shift();

document.write(JSON.stringify(arr));

4 Comments

i am curious, if i can sort the same array type that contain both string and integer.Lets say the array is like this var arr = [ ["series0", "44", "32", 56]]; After sort i would like to get the array like var arr= [["series0", "32", "44", 56]]
@user3172663 : use sort()
I am trying for arr.sort(function(a, b){return a-b}); but could not get the result as i am expecting.You can find the first element of the array is string and others are integers.
@user3172663 : add another question with relevant code
1

Try the .map function of Array:

var arr = [["series0", "44", "54",56 ]]
arr.map(function(arr){arr.shift()});
console.log(arr) 

It'll remove all the first element of all elements of outer array.

input:

 [["series0", "44", "54",56 ],["series0", "44", "54",56 ]]

output:

[["44", "54",56 ],["44", "54",56 ]]

Comments

0

Simply use the shift function:

Removes the first element from an array and returns only that element.

arr[0].shift();
alert(arr);

Comments

0

Use the array shift() method:

var arr = [["series0", "44", "54",56 ]]
arr[0].shift();      // removes and returns "series0" (return ignored here)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.