Are there any advanced functions that can loop through an array of objects and provide a boolean result?

(excluding foreach, map, reduce, filter, for, while and do while) (return true (if no object with attribute read : false is found) or false (if any one of the objects contains property read : false).) Imagine you have the following array:

let allRead = true;
let notifications = [
{message: ‘Lorem’, read: true},
{message: ‘Ipsum’, read: true},
{message: ‘Dolor’, read: true},
{message: ‘Sit’, read: false},
{message: ‘Amet’, read: true}
];

You need to change the allRead variable to false using a built-in higher-order function on the notifications array. Rules: a) You cannot utilize for, while, do-while loops b) You are not allowed to use forEach(), map(), reduce(), filter().

I've tried using some and find. It seems like find always returns the complete object, so it might not be suitable in this case.

allRead = notifications.find((obj) => {
    console.log("yes");
   if (obj.read === false) {
     console.log(obj.read);
     return obj;
   }
});
console.log(allRead);

On the other hand, utilizing some has been somewhat successful...but it only returns true when read : false is found whereas I want to set allRead to false whenever read: false is encountered, regardless of other iterations.

allRead = notifications.some((not) => not.read !== true);
console.log(allRead);

I also observed that using if else statements or switch cases and returning true/false based on conditions automatically breaks out of the loop once a certain condition is met.

allRead = notifications.some((not) => {
  switch (not.read) {
     case false:
       break;
       return false;
     default:
      return true;
    }
 });
console.log(allRead);

Answer №1

One handy method in JavaScript is Array#every, which allows you to verify whether all elements in an array meet a specific condition.

To illustrate, you can use: const allStars = ratings.every(({star})=> star);

Another useful method is Array#some; simply invert the outcome to confirm if no element matches the condition.

For example: const allPresent = !gifts.some(({given})=>!given);

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

What is the best way to assign a unique ID to every <td> element within a table using React Js?

Hello everyone. I am currently working on assigning unique ids to each td in a table based on data received through an API. This is what my code looks like so far. CodeSandbox const assignIdsToTableData = (data) => { var items = Object.values(data)[0 ...

Issue with jQuery delegate and selector

I am attempting to assign a click event to all first anchor tags in all current and future divs with the "panels" class. My approach looks like this: $('#panel').delegate('.panels a:first', 'click', function(event) [...] How ...

The Next.js application is functioning smoothly in development, but encounters errors during the building and deployment processes

While my Next.js app compiles and runs smoothly locally during development (using npm run dev), I encounter a failed build when attempting to compile the project (using npm run build). After researching online, it seems that unhandled promises may be the c ...

Emberjs: Developing a self-focusing button with Views/Handlebar Helpers

Currently, I am using a Handlebars helper view that utilizes Em.Button (although it's deprecated) to create a Deactivate Button. This button is designed to focus on itself when it appears and clicking it triggers the 'delete' action. Additio ...

Presence detected: Discord bot appears online but is missing from members list

I am embarking on the journey of creating my first Discord bot. After installing NodeJS on my computer, I used the Discord developer tools to create the app, turned it into a bot, obtained the token, selected privileges, and added the bot to my server. I ...

Creating a new Array in Scala by extracting array indices that are not next to each other

Let's explore the Scala Array x that is defined below: scala> val x = Array(10, 32, 45, 54, 44, 37) x: Array[Int] = Array(10, 32, 45, 54, 44, 37) We also have an index selection called selector, which is provided and does not include out-of-bound ...

Is it possible to use both double and int parameters simultaneously in an array?

I'm puzzled by the error showing up in the array when x is involved -line 80,96 https://i.sstatic.net/RGdLc.png public static double naiveSine(double x, int n) { //Need to figure out what's going on here double sum; double[][] NAIVE ...

Display/Conceal Dropdown Menu for Combobox Using only Javascript

In my asp.net user control, I am generating markup that looks like this: <div id="combobox1"> <div id="combobox1_text"><span>combobox 1</span></div> <div id="combobox1_ddl"> <input type="checkbox" id="combobo ...

Display radio options when clicked upon

I am in the process of creating a set of radio buttons that will be utilized for capturing values to generate a subscription/modal checkout. My current situation involves having the radio button options visible. However, I aim to achieve a functionality wh ...

Implementing vue.js to insert a new user into the user array stored in a JSON file

I'm encountering an issue with vue.js where I am unable to successfully add a new user to the user array. Despite console.logging "this.user" when calling the function on submit, I am not seeing a new box with the new user or the new user being added ...

Experiencing difficulty with the toggle menu on an HTML/CSS website. Unable to access the menu when hovering over the hamburger icon on the right side

I am experiencing an issue with the toggle button in the menu when the screen size is max-width = 1200px. Specifically, when I toggle the button, nothing appears. Can someone please assist me? I have included Bootstrap 4.3 in my HTML script. The menu that ...

Inquiries regarding my Vue testing application integrated with Supabase

I have a query regarding extracting a specific value from an array returned by Supabase. Here is the code snippet I am using: countries.value = parseInt(countries.value.map(({ aantal }) => aantal)); When I don't use parseInt, the number appears l ...

When reopening the modal in Bootstrap V5 with jQuery, the close event may not trigger as expected

When trying to implement special functionality in my modal close event using sweetalert2, I encountered an issue where the close event does not trigger again after closing the modal for the first time. Check out a live example here: https://codepen.io/th ...

Troubleshooting problem with local storage: JSON/JQuery items not appearing on display

My goal is to retrieve and organize all the items in localStorage and display them on an HTML page. Here is my approach: <script> function ShoppingCart() { var totalPrice = 0; var output; var productName; var productAlbum; var ...

Passing along the mouse event to the containing canvas element that utilizes chart.js

Recently, I created a custom tooltip for my chart.js chart by implementing a div that moves above the chart. While it works well, I noticed that the tooltip is capturing mouse events rather than propagating them to the parent element (the chart) for updati ...

Encountering Karma Angular Error: Name 'X' Not Found

After executing Karma Start in my Angular project, I am encountering several errors. All the error messages highlight issues like 'Cannot find name Blob', 'Cannot Find name KeyboardEvent', 'Cannot find name HTMLElement', amon ...

Display the initial page and activate the first navigation button when the page loads

Greetings to everyone. I am new to the world of jquery and currently in the process of learning. This is my script: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"> </script> <script> $(function () { $ ...

Ways to safeguard my Node.js Blockchain

Recently, I delved into coding my own Blockchain in order to gain a deeper understanding of the concept. You can check out my code on GitHub here: https://github.com/Snixells/js-blockchain. I've successfully implemented the creation of Blockchain + ...

Tips for transferring form element values to the ajax success callback function?

In my current project, I have implemented a system where multiple dynamic forms are submitted via ajax. The code I am using is as follows: $(document).on('submit', 'form', function (e) { $.ajax({ type: 'post', ...

When attempting to build and run in a production environment, an error message stating "Module './static' cannot be located" is displayed

I've been working on setting up the Forge-RCDB project for production environment. Using Windows Powershell, I executed the following commands: npm run build-prod $env:NODE_ENV ="production" npm start However, I encountered the following errors afte ...