Advanced .slice functionality // array.slice(-1)[0]

Hi all.

After completing the “Nested Loops” exercise, I was curious about how I could print the mutualFollowers string to the console using proper English punctuation and grammar. Therefore, I stumbled upon this code example via StackOverflow:

var a = [1, 2, 3, 4, 5];
[a.slice(0, -1).join(’, '), a.slice(-1)[0]].join(a.length < 2 ? ‘’ : ’ and ');
// ‘1, 2, 3, 4 and 5’

1 a.slice(0, -1).join(', ') : takes all but the last element and joins them together with a comma.
2 a.slice(-1)[0] : it’s the last element.
3 .join(a.length < 2 ? '' : ' and ') : joins that string and the last element with and if there are at least two elements.

My question is for the last element where ‘and’ is added. The author says that the last element is defined above in point 2 by a.slice(-1)[0]. What is the logic of using [0]? I’m assuming it is referencing a the first index in an array. Can someone help me understand the logic behind using [0] after the (-1) to accomplish this task? I understand that the values in the parenthesis indicate the index position starting with 0, and that -1 represents the last index in an array, but I’m still confused why the [0] is used on the second .slice function.
Thanks!

By the way, here it is applied to the lesson for Bob and Tina’s mutual followers and it works great:

const bobsFollowers = [‘Maria’, ‘Ross’, ‘Vince’, ‘Kees’];
const tinasFollowers = [‘Rita’, ‘Kees’, ‘Ross’, ‘Maria’];
let mutualFollowers = ;

for (let i = 0; i < bobsFollowers.length; i++){
for (let j = 0; j < tinasFollowers.length; j++){
if (bobsFollowers[i] === tinasFollowers[j]){
mutualFollowers.push(bobsFollowers[i]);
}
}
};

console.log([mutualFollowers.slice(0, -1).join(’, '), mutualFollowers.slice(-1)[0]].join(mutualFollowers.length < 2 ? ‘’ : ’ and '));
// prints: Maria, Ross and Kees

Hello, @vincanger, and welcome to the forums.

In this particular case, it appears the [0] you’re referring to is unnecessary (due to the behavior of .join()), but the difference is that the .slice() method returns an array. Adding [0] returns the first element of the array. For example:

const arr = [1, 2, 3];
console.log(arr.slice(-1)); // [ 3 ]
console.log(arr.slice(-1)[0]); // 3
1 Like