Batchguy
Batchguy

Reputation: 27

How can I order items in an array?

So I am trying to create a function that takes the first item in an array and adds an a1 to the end of it, along with the next item of the array. Then, the 3rd item gets an a2 added to it along with the fourth item, and so on. Also, I want to do this multiple times and create multiple arrays with the function parameter orderNum. I am having a hard time trying to find out how to do this, but I am guessing it has something to do with a 1 -1 1 -1 sequence. Anyway, here is my code:

function orderArray (orderNum, array) {
   var orderNum_Array = [];

   for (var i = 0; i <= array.length; i++) {
      if (Math.pow(-1, i +1) < 0) {
         array[i] = orderNum_Array [i];

         orderNum_Array[i] = orderNum_Array[i].toString();

         orderNum_Array.concat("a" + i);
      }else if (Math.pow(-1, i +1) > 0) {
         array[i] = orderNum_Array [i + 2];

         orderNum_Array[i + 2] = orderNum_Array[i + 2].toString();

         orderNum_Array.concat("a" + (i + 2));
      }
   }
}

Any and all help all would be greatly appreciated. Thanks in advance!

Upvotes: 1

Views: 162

Answers (2)

slider
slider

Reputation: 12990

It's not clear what the purpose of orderNum is, but as far as appending a1, a2 at pairs of indices is concerned, you can make this concise by using Math.ceil:

function orderArray(array) {
  return array.map((n, i) => `${n}a${Math.ceil((i + 1) / 2)}`)
}

console.log(orderArray([1, 2, 3, 4, 5, 6, 7]));

Upvotes: 1

Nikhil
Nikhil

Reputation: 6643

Your code isn't working because you are exceeding array bounds, most likely caused by orderNum_Array[i + 2].

But you can use Array.map() to do this in a simpler way.

function orderArray(array) {
   var num = 0;
   var orderNum_Array = array.map((item, index) => {
     if (index % 2 == 0) {
       num++;
     }
     return item + "a" + num;
   });
   
   return orderNum_Array;
}

console.log(orderArray([1,2,3,4,5,6]));

Upvotes: 1

Related Questions