What's wrong with the code?

Good day! The task is the following:
GetSameParity implement a function that takes as input an array of numbers and returns a new, consisting of elements that have the same parity as that of the first element of the input array.
Examples
getSameParity([]); // []
getSameParity([1, 2, 3]); // [1, 3]
getSameParity([1, 2, 8]); // [1]
getSameParity([2, 2, 8]); // [2, 2, 8]

console.log(getSameParity([1, 2, 3])); // [1, 3]

getSameParity function(arr){
 const newArr = [];
 let s;
 if(arr[1] % 0 != 0){
 s = '!=';
}else{
 s = '==';
}

 for(let i = 0; i < arr.length; i += 1){
 if(arr[i] % 0 +`${s}`+ 0){
newArr.push(arr[i]);
}
}
 return newArr;
}

I have the whole array is returned. Why?
April 3rd 20 at 17:40
1 answer
April 3rd 20 at 17:42
Solution
Because this line has not the slightest sense
arr[i] % 0 +`${s}`+ 0
First you try to get the remainder from dividing by zero instead of two, the second you make a string, and the string is always true, So it all comes back.
I understand what you want to do, but it's code you can't compile code on the fly, the right approach

getSameParity function(arr){
 const newArr = [];
 let s = arr[0] % 2;

 for(let i = 0; i < arr.length; i += 1){
 if(arr[i] % 2 === s){
newArr.push(arr[i]);
}
}
 return newArr;
}

console.log(getSameParity([3, 6, 7, 8])) // [3, 7]
console.log(getSameParity([4, 6, 7, 8])) // [4, 6, 8]


or shorter

const getSameParity = arr => arr.filter(v => v % 2 === arr[0] % 2)
Thank you that wrote me! But your code always returns a new array of the even value, and in the job stated that depending on what the first value of the input array(even/odd) from this and decide what to add into the new array. - daron_Botsford commented on April 3rd 20 at 17:45
@daron_Botsford, It is not so, in my code in the first example was a small mistake, migrated from your code, it should be let s = arr[0] % 2;

instead

let s = arr[1] % 2;

Code working - Vladimir commented on April 3rd 20 at 17:48
@daron_Botsford, well, check parity of the first number, and based on that return numbers - quentin commented on April 3rd 20 at 17:51

Find more questions by tags JavaScript