dedi wibisono
dedi wibisono

Reputation: 533

How to shift except in the first element in array Javascript?

Initial code:
var ar = [1,2,3,4,5,6]

I want to shift starting from second element and add last element. I try to using shift() and splice() but doesn't work and maybe something wrong on my code.
any idea to fix it?

thank you

var ar = [1,2,3,4,5,6];

ar.splice(5,1,"0").shift();

console.log(ar)

expected result [1,3,4,5,6,0]

Upvotes: 2

Views: 83

Answers (4)

Get Off My Lawn
Get Off My Lawn

Reputation: 36341

Maybe a little slice and concat?

var ar = [1,2,3,4,5,6];

var result = ar.slice(0, 1).concat(ar.slice(2)).concat(0)

console.log(result)

Or maybe some destructuring:

const [first, , ...next] = [1,2,3,4,5,6]

console.log([first, ...next, 0])

Upvotes: 2

ironCat
ironCat

Reputation: 161

you can try ES6 rest operator

const array = [1,2,3,4,5]  
const [firstItem, ...otherArray] = array
const newArray = [ ...otherArray, 0]


   
// or direct array assign 
// const [firstItem, ...otherArray] = [1,2,3,4,5]
   
console.log(newArray)

Upvotes: 1

Sølve
Sølve

Reputation: 4406

var ar = [1,2,3,4,5,6];

ar.splice(1,1)
ar.push(0)

console.log(ar)

Upvotes: 1

EugenSunic
EugenSunic

Reputation: 13703

var array = [1, 2, 3, 4, 5, 6];

function shift(arr, start, newElement) {
  const arr1 = []
  const rest = [];
  for (let i = 0; i < start; i++) {
    arr1.push(arr[i]);
  }
  for (let i = start + 1; i < arr.length; i++) {
    rest.push(arr[i]);
  }
  rest.push(newElement)
  return [...arr1, ...rest]
}
console.log(shift(array, 1, "0"))
console.log(shift(array, 2, "0"))

Upvotes: 0

Related Questions