+ 2

How to remove each 2nd element from an array in JavaScript and C++?

I have this weird task, remove each 2nd element from an array. [1, 2, 3, 4, 5, 6, 7, 8] becomes [1, 3, 5, 7] Some of my colleagues suggested a C++ implementation, I wonder if there is a fast solution? You can share an implementation in C++ or JavaScript. It will be great if you will describe why is your solution better or faster.

18th Apr 2018, 3:54 PM
vardanator
vardanator - avatar
6 Answers
+ 2
Mohamed May I suggest you replace alert by console.log so that vardanator can switch between the output and the code more easily without having to deal with an alert message?... Totally up to you though â˜ș
18th Apr 2018, 6:06 PM
cyk
cyk - avatar
+ 2
This is my take. I used a loop and created a new array whose content was then assigned to the original array... https://code.sololearn.com/WeYTFQBVyVe1/?ref=app
18th Apr 2018, 6:22 PM
cyk
cyk - avatar
+ 1
@Brains does this remove each 2nd element or just the first met 2nd?
18th Apr 2018, 4:20 PM
vardanator
vardanator - avatar
+ 1
let arr=[1,2,3,4,5,6,7,8]; let newarr= arr.filter(function (ele,index){ if (index%2===0) return(ele); }); console.log (newarr); // if you need to replace original array // arr=newarr.splice(""); in ES6 let newarr=arr.filter((ele,index)=>{if (index%2===0) return(ele)});
18th Apr 2018, 10:02 PM
Mike Choy
Mike Choy - avatar
0
Just the 2nd element is removed with Brains answer however it is a very good starting point. You could use a loop and go through the array and increment the parameters of splice in such a way that it does what you need
18th Apr 2018, 5:07 PM
cyk
cyk - avatar
0
Found this one interesting. In tasks like this one I usually like to keep it simple, and avoid using built-in functions. This is the simplest I could make. This code could be made to be faster, but I didnt really have time. https://code.sololearn.com/cZZVHPcSpv4N/?ref=app
21st May 2018, 4:21 PM
Kljova
Kljova - avatar