KingOfLeon
KingOfLeon

Reputation: 35

JavaScript push() issue

Can you tell me please, why the final array does not have the last item of the initial array; it returns [3, 6, 9, 2, 4, 6], and we are missing '8'.

let item = [123,456,789,12,34,56,78];
const tailAndHead = arr => arr.slice(1).reduce((a,v,i) => (a.push(arr[i]%10), a),  []);

Upvotes: 1

Views: 76

Answers (3)

Redu
Redu

Reputation: 26201

You should push the sliced array item. Please modify you code like this.

let item = [123,456,789,12,34,56,78];
const tailAndHead = arr => arr.slice(1).reduce((a,v,i,b) => (a.push(b[i]%10), a),  []);
console.log(tailAndHead(item));

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386883

Why not use Array#map?

tailAndHead = arr.map(a => a % 10);

Upvotes: 3

Sabith
Sabith

Reputation: 1656

Remove slice(1).

let item = [123,456,789,12,34,56,78];

const tailAndHead = arr => arr.reduce((a,v,i) => (a.push(arr[i]%10), a),  []);

Upvotes: 2

Related Questions