Determine whether there are a minimum of two elements in the array that are larger than zero - JavaScript/Typescript

Looking for an efficient way to determine if there are at least two values greater than 0 in an array and return true? Otherwise, return false. Here's a hypothetical but incorrect attempt using the example:

const x = [9, 1, 0];
const y = [0, 0, 0];
const z = [5, 0, 0];

const checkValues = (element) => element > 0 && somethingElseMaybe;

console.log(x.some(checkValues)); // expected output: true
console.log(y.some(checkValues)); // expected output: false
console.log(z.some(checkValues)); // expected output: false

Answer №1

Utilize the filter() method to eliminate values that are below zero and then verify if the resulting array has a length of two or more

const checkGreater = arr => arr.filter(x => x > 0).length >= 2;

console.log(checkGreater([9, 1, 0])) //true
console.log(checkGreater([0, 0, 0])) //false
console.log(checkGreater([5, 0, 0])) //false

Answer №2

In order to prevent wasting effort, it is advisable to halt the checking process once the condition has been satisfied. I believe this solution aligns with your requirements.

function checkIfTwoGreaterThanZero(arr) { 
    let count = 0;
    for(let num of arr) {
        if(num > 0 && (++count > 1)) return true;
    }
    return false;
}

const array1 = [9, 1, 0];
const array2 = [0, 0, 0];
const array3 = [5, 0, 0];

console.log(checkIfTwoGreaterThanZero(array1)); // expected output: true
console.log(checkIfTwoGreaterThanZero(array2)); // expected output: false
console.log(checkIfTwoGreaterThanZero(array3)); // expected output: false

Answer №3

If you prefer not to loop through the entire array, you can utilize a loop and break out of it early once your condition is met. While using filter may be more elegant, in cases where the list is extremely large, there could be benefit in not iterating through the whole array.

I have deconstructed this function into its fundamental components and developed a curried version.

The main question at hand is "whether there are 2 or more values that are greater than 0 in the array." However, this can be simplified to "are there X or more values that fulfill the comparator"?

const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const quantityCompare = compare => quantity => arr => {
  let count = 0;
  for (let i = 0; i < arr.length; i += 1) {
    if (compare(arr[i])) count += 1;
    if (count >= quantity) return true;
  }
  return false;
};

const twoElementsGreaterThanZero = quantityCompare(x => x > 0)(2);

console.log(twoElementsGreaterThanZero(a)); // true
console.log(twoElementsGreaterThanZero(b)); // false
console.log(twoElementsGreaterThanZero(c)); // false

Just for fun, another alternative is to utilize Array.some (similar to an Array.forEach with the ability to exit early):

const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const quantityCompare = compare => quantity => arr => {
  let count = 0;
  return arr.some(el => {
    if (compare(el)) count += 1;
    if (count >= quantity) return true;
  })
}

const twoElementsGreaterThanZero = quantityCompare(x => x > 0)(2);

console.log(twoElementsGreaterThanZero(a)); // true
console.log(twoElementsGreaterThanZero(b)); // false
console.log(twoElementsGreaterThanZero(c)); // false

Answer №4

If you find yourself needing to perform tasks like this frequently, consider creating your own method for generating predicate functions. One approach is to create a main function that generates functions which return true or false based on whether an array meets a certain condition:

function minimumSatisfy(condition, minimum) {
  return function(array) {
    for (var i = 0, count = 0; i < array.length && count < minimum; i++) {
      if (condition(array[i]))
        count++;
    }
    return count >= minimum;
  }
}

To apply this concept to your specific scenario, create a custom function using the main function:

let twoGreaterThanZero = minimumSatisfy(value => value > 0, 2);

You can now use this new function to evaluate any array with the specified predicate:

if (twoGreaterThanZero(someArray)) {
  // ...
}

However, if you only need to perform this type of check in one part of your code, it may not be necessary to implement this solution.

Answer №5

Give it a shot

var x = [7, 2, 1]
var y = [3, 4, 5]
var z= [6, 7, 8]

function checkDuplicateElements(arr, element) {
  return arr.indexOf(element) !== arr.lastIndexOf(element)
}

console.log(checkDuplicateElements(x, 1))
console.log(checkDuplicateElements(y, 3))
console.log(checkDuplicateElements(z, 8))

Answer №6

Give this a shot,

console.log(a.filter(s => s > 0).length >= 2); // output is true
console.log(b.filter(s => s > 0).length >= 2); // output is false
console.log(c.filter(s => s > 0).length >= 2); // output is 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

Customizing object joining rules in JavaScript arrays

My array consists of different colored items with their respective types and amounts [ { color: 'blue', type: '+', amount: '1' }, { color: 'blue', type: '-', amount: '1' }, { color: 'blu ...

Capture a screenshot of the icons

I'm curious about displaying specific parts of images in a React Native application. class InstaClone extends Component { render() { return( <View style={{ flex:1, width:100 + "%", height:100 + "%" }}> <View style={st ...

What is the correct method for typing sagas?

After diligently following the official redux documentation for integrating with TypeScript, which can be found at https://redux.js.org/recipes/usage-with-typescript, I successfully typed actions, reducers, react components, and more. However, my progress ...

What is the most effective method to retrieve the current browser URL in Angular 2 with TypeScript?

Is there a way for me to retrieve the current URL from the browser within my Angular 2 application? Usually in JavaScript, we would use the window object for this task. Can anyone guide me on how to achieve this in Angular 2 using TypeScript? Appreciate a ...

Transferring information between components and pages within Next.js involves the passing of data

I currently have an index page set up like this: getServerSideProps(){ //Making two API calls here api1() api2() return{ props:{data:gotDataApi1, data2:gotDataApi2} } } The data retrieved from these APIs is then passed to a component within the index pag ...

Bringing in SCSS using Typescript, React, and Webpack

I am trying to utilize .scss classes by importing them and applying them to the className property of a React component. Here is the structure of my project : root/ ... config/ ... webpack.config.js src/ ... global.d.ts app/ ...

Combining the power of jQuery, PHP, JavaScript, and the popular WordPress platform, let's unlock

After going through numerous attempts to find answers for similar issues, I'm unable to get any of the suggested solutions to work. My WordPress site requires a plugin that utilizes jQuery. The main file for my plugin is located at wp-content/plugins ...

Cross-origin resource sharing in Express.js servers

Encountering a minor issue with the connection setup between my Express.js API and React client. The Express API is running on http://localhost:3001, while React is hosted at http://exampleip:3000 (both on the same Windows server). To address Cross-Origi ...

Ways to adjust the width of the Dialog box in Jquery UI to 60% of the window size

Currently, I am utilizing Jquery UI for a pop-up feature that displays a table populated through an Ajax call. The script implementation is as follows: <script> $(function() { $( "#dialog" ).dialog({ autoOpen: false, show: { ...

What is the method for setting a default image to be preloaded in filepond?

Currently, I am working on a Laravel view for editing a record which includes an associated image. My goal is to have the image preloaded inside the input file so that when you submit the form, the same image is sent or you can choose to change it. // Con ...

Update the form action URL when a specific option is selected from the dropdown menu upon clicking the submit

I would like my form to redirect to a specific page on my website based on the selection made in the <select> tag. For instance, if '2checkout' is selected, it should go to gateways/2checkout/2checkout.php. Similarly, if 'Payza' i ...

Unable to load connected modules from npm/yarn link within the WSL environment

Trying to import a local dependency into my project is proving to be quite challenging. The situation at hand involves a project named 'test_project' and another one called 'test_module'. Linking test module to the global node_modules ...

Mastering the art of looping through JSON values using AngularJS ng-repeat

Is there a way to use ng-repeat in order to iterate and access the name values: test01, test02, and test03 from my JSON data? Any guidance on how to achieve this using ng-repeat would be greatly appreciated. Thanks in advance! Check out this Fiddle link. ...

The Angular 5 lifecycle hook ngOnChanges is triggered just once in a child component

I am struggling with syncing a child component containing complex input (such as chart data) with the API response received in the parent component in Angular 5. I am using the @Input() decorator to pass the chart data from the parent to the child componen ...

When attempting to modify the state in a parent component from a child using the composition API in Vue 3, the error "this.$emit() is not a

//Main component <template> <childComponent @onChangeData='updateData' /> </template> <script> setup() { const state = reactive({ data: 'example' }); function updateData(newValue){ s ...

Tips for utilizing ng-repeat with a function that generates a fresh object?

My HTML code includes the following element: <button ng-click="console.log(key)" ng-repeat="(key, value) in getLocalStorageKeys() track by $index"> In my JavaScript file, I have the following function: $scope.getLocalStorageKeys = function(){ ...

What is the reason behind material-ui's decision to invoke their dialogs twice?

After attempting to implement a modal and realizing the strange behavior, I switched to using a dialog instead. To my surprise, the issue persisted. This is how I approached it: import Dialog, { DialogProps } from '@material-ui/core/Dialog'; imp ...

Error Message: React encountered an issue when trying to access the 'theme' property of an undefined object

Currently developing a web application using React, I encountered an issue when trying to implement the react-datepicker component in my code. Upon adding the following lines of code, my web application breaks and an error is thrown: import {SingleDatePic ...

Shopify module is throwing an error stating that React is not defined

I wanted to create my first Shopify module, but I encountered an error in my application page on the shop while using React. Here is my index.js code: import {Page} from "@shopify/polaris"; import {ResourcePicker} from "@shopify/app-bridge- ...

Can one jQuery script be used for multiple ajax 'like' buttons?

Hey there! I'm working on an Ajax 'like' button that utilizes jQuery. This button will be utilized multiple times on a single page. I'm looking for a way to streamline the process and avoid including the jQuery script multiple times. Is ...