I am learning the basics and I just cannot hack this one:
This function will be called with an array and should return a new array containing only the alternate elements starting from index 0. If the array is empty or contains only 1 item, return the original array.
makeAlternatingArray(['hey', 'hi']);
// should return ['hey']
makeAlternatingArray(['a', 'b', 'c', 'd', 'e']);
// should return ['a', 'c', 'e']
What I got so far is:
function makeAlternatingArray(array) {
if (array.length<=1){
return array
}
for (let i=0; i<array.length; i=+2){
return array[i]
}
}
Top part is correct but by for let statement is wrong. I am getting these errors:
When passed an array of multiple elements, function will return an array of alternating items
✕ AssertionError: expected ‘a’ to deeply equal [ ‘a’, ‘c’, ‘e’ ]
When passed an array of multiple elements, function will return an array of alternating items
✕ AssertionError: expected 100 to deeply equal [ 100, 99, -5 ]
Can someone help please?
function makeAlternatingArray(array) {
if (array.length<=1){
return array
}
for (let i=0; i<array.length; i=+2){
return array[i]
}
}
>Solution :
function makeAlternatingArray(array) {
if (array.length<=1){
return array
}
return array.filter((el, i) => i % 2 === 0);
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
or
function makeAlternatingArray(array) {
if (array.length<=1){
return array
}
let newArray = [];
for (let i=0; i<array.length; i=+2){
newArray.push(array[i]);
}
return newArray;
}