0

I am trying to interchange array and print it using shift method but not sure whether I can use it or not.

Code Snippet below.

var points = [40, 100, 1, 5, 25, 10];

//trying to achieve like anotherPoints array
//var anotherPoints = [1, 5, 100, 40, 25, 10];

for (index = 0; index < points.length; index++) {
  points.shift();
  console.log(points);
}
Aleksandr M
  • 24,264
  • 12
  • 69
  • 143

2 Answers2

0

The shift() method doesn't shift or interchange the elements of an Array. It is similar to pop(), but it pops out the first element from the Array.

For example,

var points = [40, 100, 1, 5, 25, 10];
console.log(points.shift());  // 40
console.log(points); // [100, 1, 5, 25, 10]

As to your requirement of rearranging the elements of an Array, you will have to use Array.splice() method. Check out this question Reordering arrays.

Community
  • 1
  • 1
viveksn
  • 1
  • 3
0

Some logic to get the desired result:

var points = [40, 100, 1, 5, 25, 10],
    temp1 = [], temp2 = [], anotherArray;
points.forEach(function(val){
    if(val < 10 ) {
        temp1.push(val)
    } else {
        temp2.push(val);   
    }
});
anotherArray = temp1.sort().concat(temp2.sort(function(a,b){return b- a}));
alert(anotherArray);

It's not possible via shift or splice. Unless manually creating the array.

mohamedrias
  • 18,326
  • 2
  • 38
  • 47