Eloquent JavaScript Chapter 5 Poser: Can you solve the exercise question using the array.some method

This particular challenge really had me scratching my head for a while. After struggling with it, I finally caved and resorted to looking up the solution online. The hint provided was quite cryptic, and dealing with "De Morgan's Laws" in JavaScript using &&, !, and || proved to be quite complex. While I'm starting to grasp the concept, I still have a ways to go before fully understanding it. It seems like I'll need plenty of practice and time to master these ideas completely. Here is the question from one of the exercises at the end of chapter 5:

Similar to the some method, arrays also come equipped with an every method. This function returns true only when the specified function evaluates to true for each element within the array. In essence, some behaves like the || operator for arrays, whereas every functions similarly to the && operator.

Your task is to implement the every function that takes an array and a predicate function as arguments. You are required to create two versions: one utilizing a loop and the other making use of the some method.

function every(array, test) {
  // Your implementation here.
}

console.log(every([1, 3, 5], n => n < 10));
// → true
console.log(every([2, 4, 16], n => n < 10));
// → false
console.log(every([], n => n < 10));
// → true

I managed to successfully complete the first version by employing array.every; it wasn't too challenging. However, I'm still struggling to comprehend the solution involving the some method. Here's how the second part of the question should be tackled:

function every(array, test) {
    return !array.some(element => !test(element));
}

I've been working through this in my mind, but I could really benefit from someone on Stack Overflow guiding me through the thought process. Can anybody provide some insight into what exactly is happening here?

Thanks in advance!

Jordan

Answer №1

One way to solve this is by creating a truth table and observing the results for different values.

In the following example, we take the second scenario and illustrate the intermediate result for the first two elements, assuming that the loop would terminate at that point and yield the final result.

            n < 10               !(n < 10)
  value    compare1     every     compare2    some       !some    comment
---------  ---------  ---------  ---------  ---------  ---------  -------------------
     2        true                 false 
     4        true                 false

                         true                 false       true    intermediate result

    16       false                  true

                        false                  true      false    final result
                        ^^^^^                            ^^^^^

By applying De Morgan's laws, it is possible to transform a term by switching between the logical AND && and the logical OR || operators or by negating all values in the expression.

a && b && c
!(!a || !b || !c)

Both expressions are equivalent (for boolean values).

Array#every behaves like using &&, while Array#some acts like ||.

To convert some into every, the condition inside the callback needs to be negated along with the final result.

Answer №2

Presently, I am tackling this particular challenge. Based on the criteria outlined for option 1, it is not feasible to utilize the Array.every() method. Therefore, a custom function must be created to mimic the functionality of Array.every(). Below are the potential solutions I have devised: I would greatly appreciate any advice or guidance regarding potential errors in my approach.

let numbers1 = [3, 4, 9, 7];
let numbers2 = [3, 4, 1, 7];

function every2(array, predicat) {
    if (array.constructor !== Array) return "not array";
    let result = Boolean;
    for (let i = 0; i < array.length; i++) {
       result = predicat(i);
       if (!result) break;
    }
    return result;
}

console.log(every2(numbers1, (i => numbers1[i] > 2)));  //true
console.log(every2(numbers2, (i => numbers2[i] > 2)));  //false

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add HTML and JavaScript code dynamically with JavaScript

Currently, I am working on a project that involves an HTML table with some basic JS interactions triggered by user clicks. The structure looks something like this: htmlfile.html ... ... position action ...

Retrieve data from HTML Form arrays using JavaScript

I have a situation in my forms where arrays are being sent back in the following format: <input class="checkbox-service" name="services['electricity']" type="checkbox"> <input class="checkbox-service" name="services['water'] ...

What are the reasons behind the inability to import an image file in Next.js?

Having an issue with importing image file in Next.js I'm not sure why I can't import the image file... The image file is located at 'image/images.jpg' In Chrome browser, there are no error messages related to the image, However, in ...

What is the purpose of incorporating the replace function in my regular expression for Palindromes?

I'm currently tackling some challenges on FreeCodeCamp and I've hit a roadblock in a simple task which requires checking for palindromes. The solution provided involves the following step: str = str.replace(/[^a-zA-Z]/g, '').toLowerCas ...

Angular 4 is unable to attach to 'formGroup' as it is not recognized as a valid property of 'form'

As a beginner with Angular 4, I decided to explore model driven forms in Angular 4. However, I keep encountering this frustrating error. Template parse errors: Can't bind to 'formGroup' since it isn't a known property of 'form ...

The splash screen fails to show up when I launch my Next.js progressive web app on iOS devices

Whenever I try to launch my app, the splash screen doesn't show up properly. Instead, I only see a white screen. I attempted to fix this issue by modifying the Next Metadata object multiple times and rebuilding the PWA app with no success. appleWebApp ...

Is there anyone who can provide a solution for addressing CORS problems when using React with Express?

I've been working on integrating Postman with React JS using express. I've been following a Mern Stack Development tutorial on freeCodeCamp. Both Chrome and Edge have the CORS extension enabled, but I keep running into the error message "Cannot g ...

How can I modify my for loop with if else statements so that it doesn't just return the result of the last iteration in

Today is my first day learning JavaScript, and I have been researching closures online. However, I am struggling to understand how to use closures in the code I have written: function writeit() { var tbox = document.getElementById('a_tbox'). ...

What is Flask's approach to managing JSON data?

I am currently developing an editable table using FLASK, JSON, and jQuery. After serializing the form, I send it via $.getJSON, as shown at the bottom of my JS code: This is the JS code: $(function(){ $('tbody').on('click', &apos ...

Ways to modify a link tag based on a specific browser width

Looking for a solution to optimize the drop-down sign in box code that gets appended to a hamburger menu when the mobile width media query is called. Can we refactor this to switch the drop-down sign in box to just an anchor tag (<a href="signin">< ...

Utilizing RxJs operators in Angular: utilizing async pipe and tap does not fill data

Here is a code snippet I've been working on: This snippet is written in Typescript: isDataSearch = false; getDatacollectionByID() { const params = { id: <some random ID>, }; this.metaData = this.dataService.getDatacollectionByID(par ...

Is it possible to include a component in an HTML file when the constructor of the component needs a parameter?

Recently delving into the world of AngularJs has been a captivating experience for me. I am aiming to develop a component with a constructor that accepts a parameter of type string. However, when I try to declare the selector on the HTML file, the componen ...

Enhancing jQuery's ScrollTop Functionality

My jQuery script for scrolling to the top of a container seems to accelerate after it starts. It begins slowly and then speeds up. Is there a way to prevent this lag at the beginning and maintain a consistent speed throughout the entire scroll? // Once t ...

The POST request gets interrupted

Having an issue with my post request in JavaScript. Below is the code I am using to send the post request: var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this ...

What is the reason for Array.count not being a UInt?

What is the reason behind Array.count being an Int and not a UInt? Is there any scenario where the value of Array.count could be negative? ...

Removing a value from an array contained within an object

I have a scenario in my task management application where I want to remove completed tasks from the MongoDB database when a logged-in user marks them as done. Below is the snippet of code for my Schema. const user = new mongoose.Schema({ username : Str ...

Encountering Access Violation Issue while Attempting to Read a String in C

According to the book: How to C Programming - Eighth Edition (by Deitel brothers) this code reads the word "Hello": #define SIZE 20 int main() { char MyStr[SIZE]; printf("Enter your word: "); scanf("%19s", MyStr); } This image is sourced from ...

What is causing my HTML script tag to not recognize my JS file in Next.js?

Just starting out with Next.js and trying to access the web cam for a project I'm working on, but encountering an issue when writing in the "script" tag. Below is the simple code for page.js: export default function Live(){ return( <html> ...

What could be causing the res.sendfile() method to fail when invoked through a jQuery ajax call?

Problem: The first ajax call in the main.js is functioning correctly, but there seems to be an issue with the second one. Although it appears to be working initially, I suspect that there may be a bug present. Upon clicking the button, I am able to access ...

Separate mathematical expressions into an array without breaking apart any subexpressions inside parentheses or single quotes

Consider this given string: 1 + 2 * (3 + (23 + 53 - (132 / 5) + 5) - 1) + 2 / 'test + string' - 52 The task is to divide the string into an array of operators and non-operators, while preserving the content between () and '. The desired ou ...