Not sure why this code does not work edit* it is supposed to return only odd elements in an array
function findOdd(A) {
var arr = [];
for (var i=0; i<A.length; i++){
if(arr.indexOf(A[i]) == -1){
arr.push(A[i]);
}
else {
arr.splice(A[i],1);
}
}
return arr;
}
For test case findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]) should return 5. However it returns [20, -1, 3, 5]. Any idea as to why this doesn't work as I think it should? Thank you.
You just need to change this line
arr.splice(A[i],1);
to
arr.splice(arr.indexOf(A[i]),1); //remove it from index of this element since splice is taking index rather than element itself.
DEMO
function findOdd(A) { var arr = []; for (var i=0; i<A.length; i++){ if(arr.indexOf(A[i]) == -1){ arr.push(A[i]); } else { arr.splice(arr.indexOf(A[i]),1); } } return arr; }; var output = findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]); console.log( output );
You may also do the job very efficiently as follows;
In this particular case the hash
object produced by the .reduce()
looks like
{ odd : { '1': 0, '2': 0, '3': 0, '4': 0, '5': 3, '20': 0, '-1': 0, '-2': 0 },
even: { '1': 2, '2': 2, '3': 2, '4': 2, '5': 0, '20': 2, '-1': 2, '-2': 2 } }
Ond the Object.keys()
part collects the required information from the hash.odd
sub object.
function oddMany(a){ var hash = a.reduce((h,n) => h.odd[n] ? (h.even[n] = h.odd[n] + 1, h.odd[n] = 0, h) : (h.odd[n] = h.even[n] + 1 || 1, h.even[n] = 0, h), {odd:{},even:{}}); return Object.keys(hash.odd).reduce((r,k) => hash.odd[k] ? r.concat(k) : r ,[]); } var arr = [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]; console.log(oddMany(arr));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.