Determine the length of the result from using the Array.prototype.some() method

I have a conditional that is being checked using Array.prototype.some(). Take this array for example:

const coolArray = [
  { isCool: false },
  { isCool: false },
  { isCool: true }
]

const isCool = coolArray.some(item => item.isCool === true)

if (isCool) {
  console.log("Hello, I'm considered cool!")
}

But what if I want the check to only pass when item.isCool is true and at least two items in the array meet this condition? In such a case, the message would not be outputted as there's only one true condition.

The MDN documentation states that the syntax of this method is

arr.some(callback(element[, index[, array]])[, thisArg])
. However, the reference to [, array] in the callback function pertains to the original array instead of its clone. Therefore, modifying the code snippet like below yields the same result:

const isCool = coolArray.some((item, index, arr) => {
  return item.isCool === true && arr.length > 1
})

I understand that I could bypass using .some() and iterate over the array with map or for loops while storing results in an external array for later length comparison. A sample implementation is shown below:

const isCoolArr = []
coolArray.map(item => item.isCool ? isCoolArr.push(item) : false)
console.log('Expected outcome:', isCoolArr.length) // outputs 1

However, I am seeking simpler alternatives to achieve this. Is .some() suitable for my requirements, or should I consider other approaches apart from the ones mentioned earlier?

Answer №1

Using Array.reduce

const awesomeArray = [
  { isAwesome: false },
  { isAwesome: true },
  { isAwesome: true }
]

const total = awesomeArray.reduce((sum, element) => Number(element.isAwesome) + sum, 0)

if (total >= 2) {
  console.log("Hey there, I'm awesome!")
}

Answer №2

When using .filter(), you do not have the advantage of short-circuiting that comes with .some(). One way to work around this is by utilizing a variable outside of the callback function.

const coolArray = [{isCool: false},{isCool: false},{isCool: true}]
let count = 0

const isCool = coolArray.some(item => (count += item.isCool) >= 2)

if (isCool) {
  console.log("hello I'm cool!")
} else {
  console.log("not cool enough")
}

This technique leverages the conversion of booleans into numbers. If you prefer a more explicit approach, there is an alternative available.

const coolArray = [{isCool: false},{isCool: false},{isCool: true}]
let count = 0

const isCool = coolArray.some(item => item.isCool && ++count >= 2)

if (isCool) {
  console.log("hello I'm cool!")
} else {
  console.log("not cool enough")
}

Another option is to achieve the same result without adding an extra variable.

const coolArray = [{isCool: false},{isCool: false},{isCool: true}]
let isCool = 0;

isCool = coolArray.some(item => item.isCool && ++isCool >= 2);

if (isCool) {
  console.log("hello I'm cool!")
} else {
  console.log("not cool enough")
}

Answer №3

One way to achieve this is by using the filter method and then checking the length of the resulting array

const coolArray = [
  { isCool: false },
  { isCool: false },
  { isCool: true }
]

const isCool = coolArray.filter(item => item.isCool === true)

if (isCool.length > 1 ) {
  console.log("hello I'm cool!")
} else{
  console.log('length is less than 2')
}

Answer №4

Some individuals have recommended using the filter function and checking for the length. I propose creating a custom method called atLeast, which will stop once the condition is satisfied.

const amazingArray = [
  { isAmazing: false },
  { isAmazing: false },
  { isAmazing: true }
]

function checkCondition(cb, num) {
  let count = 0;
  for (let i = 0; i < this.length; i++) {
    if (cb(this[i], i, this)) count++;
    if (count === num) return true;
  }
  return false;
}

Object.defineProperty(Array.prototype, 'atLeast', {
  value: checkCondition,
  writeable: true
})

console.log(amazingArray.atLeast(x => x.isAmazing === true, 1)); //true
console.log(amazingArray.atLeast(x => x.isAmazing === true, 2)); //false

Answer №5

Here is a basic implementation that terminates when the specified limit is reached:

let stopAtLimit = (array, fn, count) => array.some(x => !(count -= Boolean(fn(x))));

console.log(stopAtLimit(
    [1,2,3,44,5,66,7,99],
    x => x > 10,
    2
))

Alternatively,

let checkLimit = (fn, count) => x => !(count -= !!fn(x));
    

console.log(
    [1, 2, 3, 44, 5, 66, 7, 99].some(checkLimit(x => x > 10, 2))
)

In most scenarios, the premature exit optimization may not be necessary, and you can resort to using a more general counter function like this:

let countMatching = (array, fn) => array.reduce((n, x) => n + Boolean(fn(x)), 0);

console.log(countMatching(
    [1,2,3,44,5,66,7,99],
    x => x > 10
) >= 2)

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

Remove rows from a 2d array that do not include a particular value

I am working with a multidimensional haystack array that looks like this: [ 4 => [0, 1, 2, 3, 10], 1 => [0, 1, 2, 3, 10], 2 => [0, 1, 2, 3], 3 => [0, 1, 2, 3] ] If I have a search value of $x = 10, What is the best way to sear ...

Making an Ajax request to trigger a method within a controller

Here is the code snippet I wrote: $(function () { $("input#Submit1").on('click', function () { $.ajax({ url: 'Home/GetPort', method: 'GET' }); alert("test") ...

Ways to eliminate redundant older React components within a different library

Having trouble with material-ui in my React project as I encounter this error. Error: Invalid hook call. Ensure hooks are only called inside the body of a function component. Check for: Possible mismatch of React and renderer versions (i.e., React DOM) ...

Can a form be selected and submitted using only its class as a selector?

When trying to select and submit a form using only the class as a selector, I encountered an issue: $("form.class").submit(...) doesn't seem to work... however: $("form#id").submit(...) works perfectly fine. Any idea what could be causing this di ...

PHP's json_encode function is returning an empty array for the first index retrieved from a MySQL table

Greetings, I am new to PHP and I'm currently attempting to retrieve data from a MySQL table as an array of JSON. Although I successfully managed to obtain the array of JSON from the PHP file, there seems to be an empty array present at the first index ...

The initial step is duplicated in both "Intro.js" and "Intro.js-react"

The problem is as follows: Upon reloading, a pop-up appears in the upper left corner with an incorrect progress bar displaying 0, as shown in the screenshot below. https://i.sstatic.net/djCyf.png If you click on "Next", the same content reappears but th ...

Issue with data updating in Angular rxjs with share, map, and filter functions

After gathering search criteria from a form, I have developed a method that retrieves an observable of talents. fetchTalents(searchCriteria) { return this._allUsers$.pipe( tap((talents) => console.log(talents)), map((tale ...

Strange error message: Attempting to set properties of null (changing 'innerHTML')

I have been working on a project where I am creating a website that retrieves data from a specified URL, displays it on the front end, and performs certain functionalities with that data (although this part is not yet implemented). However, I have encounte ...

What are some ways to establish a connection with the store in components that are not using React

It's been a struggle trying to connect to the store using non-react components. Whenever I attempt to use getState or dispatch in a non-react class like this: createStoreWithApi(api).dispatch(isLoading(true)), it ends up creating a new instance of the ...

What is the best way to graph a 2D array by converting it into two separate 1D arrays?

I need to split the Latitude and Depth data into two separate numpy arrays. [['Latitude' 'Depth'] ['28.00303425' '5067.9097'] ['28.00304059' '5068.656'] ... ['28.01996016' '5067 ...

Unearthing the worth of the closest button that was clicked

I am currently working on a profile management feature where I need to add students to the teacher's database. To achieve this, I am using jQuery and AJAX. However, I am encountering an issue where clicking the "add" button for each student listed on ...

Algorithm in Java to calculate the total number of bits in a byte array

I have been struggling to find a solution to this particular issue related to Java on the internet. The problem seems simple enough - I need a method to count the number of bits in a byte array of any size. The byte array may contain hexadecimal, decimal, ...

Executing a JavaScript function within PHP code

I am working on a foreach loop that creates a series of checkboxes with items from a database. Currently, none of the checkboxes are pre-checked and each time a user checks one, a JavaScript function is called. Now, my clients want the first checkbox to b ...

Trouble arises when trying to create an auto suggest text box using PHP and Javascript

I've been working on creating a basic auto-suggest input feature that connects to a MySql database to retrieve data. However, I'm facing a particular issue where when I enter the name of an object that I know exists in the database, the input bar ...

combine jquery to simultaneously crossfade two divs in a single function

My jquery script successfully creates a rotating/fading effect for one div on the page, but I am struggling to implement the same effect for a second div. Here is my current code: $(window).load(function() { setInterval('cycleImages()', 5000); } ...

What is the best way to ensure blocking on an AJAX call?

When it comes to Ajax, callbacks are used due to its asynchronous nature. I desire my request to the remote URL to wait until a response is received, akin to how Ajax operates, but without the asynchrony. In other words, I seek to create a JAX call. Is t ...

Exploring the world of mongoose searching

Currently, I am setting up a search functionality for a Mongodb database using Mongoose. Here's what I have on the frontend: var searchQuery = { title: ($('#responseTitle').val()), text: ($('#responseKeywords&ap ...

Toggle the visibility of a button embedded within an ng-repeat loop

I am attempting to display or hide buttons within an ng-repeat loop, specifically in a simple table. I want to replace a delete button with a confirm button. Below is my code: ..... Angular stuff ..... function ContactsCtrl($scope, $http) { $scope.o ...

Error: Material UI encountered a problem with type error - number 0 cannot be iterated (property Symbol(Symbol.iterator) cannot be read)

I am currently working with the MUI(Material UI) App bar. You can find it here. The version I am using is v6.1.1. In the sandbox environment, everything seems to work fine when testing. However, when implementing it into my project, I encounter the follo ...

How can I implement image visibility toggling on click with AngularJS version 1?

My goal is to create a feature where clicking on an image will bring it to the front, hiding all other images behind it. I have found a code reference for achieving similar functionality using jQuery. Click on image to move to front? Can anyone provide ...