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

Find if Exactly One Element in An Array Is True

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

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

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