Write a function one that accepts an array and a callback as arguments. The function should call the callback for each element of the array, passing in the element and its index. The function should return a boolean indicating whether or not exactly one element of the array results in true when passed into the callback.
This is what I’ve written so far:
function one(array, cb) {
for (let i = 0; i < array.length; i++) {
let element = cb(array[i]);
if (element === true) {
return true;
}
}
return false;
}
let result1 = one(['x', 'y', 'z'], function(el) {
return el === 'a';
});
console.log("1 F:" + result1); // false
let result2 = one(['x', 'a', 'y', 'z'], function(el) {
return el === 'a';
});
console.log("2 T:" + result2); // true
let result3 = one(['x', 'a', 'y', 'a', 'z'], function(el) {
return el === 'a';
});
console.log("3 F:" + result3); // false
let result4 = one(['apple', 'dog'], function(el) {
return el.length > 3;
});
console.log("4 T:" + result4); // true
let result5 = one(['apple', 'dog', 'pear'], function(el) {
return el.length > 3;
});
console.log("5 F:" + result5); // false
let result6 = one(['apple', 'dog', 'food', 'cat'], function(el, idx) {
return el.length === idx;
});
console.log("6 T:" + result6); // true
>Solution :
You could filter the array by cb and check that the length is 1.
function one(array, cb) {
return array.filter(cb).length === 1;
}
let result1 = one(['x', 'y', 'z'], function(el) {
return el === 'a';
});
console.log("1 F:" + result1); // false
let result2 = one(['x', 'a', 'y', 'z'], function(el) {
return el === 'a';
});
console.log("2 T:" + result2); // true
let result3 = one(['x', 'a', 'y', 'a', 'z'], function(el) {
return el === 'a';
});
console.log("3 F:" + result3); // false
let result4 = one(['apple', 'dog'], function(el) {
return el.length > 3;
});
console.log("4 T:" + result4); // true
let result5 = one(['apple', 'dog', 'pear'], function(el) {
return el.length > 3;
});
console.log("5 F:" + result5); // false
let result6 = one(['apple', 'dog', 'food', 'cat'], function(el, idx) {
return el.length === idx;
});
console.log("6 T:" + result6); // true