1
let array=[3,5,2,6,1,7,4]; // output "1,7,2,6,3,5,4"
let pivot = 4;
console.log(array);
let ascending=[];
let descending=[];
let new_array=[];

for(let i=0;i<array.length;i++){
    if(array[i]<pivot){
        descending.push(array[i]);
    }
    else if(array[i]>pivot){
        ascending.push(array[i]);
    }  
}
descending.reverse();
ascending.reverse();

console.log(descending); // reversed descending value 1,2,3
console.log(ascending); //  reversed ascending value 7,6,5

Hello i want to shift the values from original array that is [3, 5, 2, 6, 1, 7, 4] to use the ascending array while looping if the array[i] is bigger than 4 to use 7,6,5 and when its smaller than 4 to use descending array of 1,2,3 so the outcome will be 1,7,2,6,3,5,4

  • does this help: https://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function ? – georg Mar 19 '18 at 19:39

1 Answers1

0

This produces the exact result you want to achieve:

let array = [3, 5, 2, 6, 1, 7, 4]; // output "1,7,2,6,3,5,4"
let pivot = 4;
console.log(array);
let ascending = [];
let descending = [];
let new_array = [];

for (let i = 0; i < array.length; i++) {
  if (array[i] < pivot) {
    descending.push(array[i]);
  } else if (array[i] > pivot) {
    ascending.push(array[i]);
  }
}
descending.reverse();
ascending.reverse();

console.log(descending); // reversed descending value 1,2,3
console.log(ascending); //  reversed ascending value 7,6,5

let newArr = [];
for (let i = 0; i < ascending.length || i < descending.length; i++) {
  if (descending.length > i) newArr.push(descending[i]);
  if (ascending.length > i) newArr.push(ascending[i]);
}
newArr.push(pivot);
console.log(newArr);
Sebastian Speitel
  • 7,166
  • 2
  • 19
  • 38