Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

To Make alternating array

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’ ]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading