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);
}

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

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