Verify whether the elements of an array satisfy a condition only when they are adjacent in a JavaScript program

Consider the following array :

[500, 250, 380, 250, 230, 100, 700, 900, 200, 100, 10, 800, 5]

My goal is to extract all values less than 350 that are contiguous. Here is the desired result :

[[250], [250, 230, 100], [200, 100, 10], [5]]

This is what I have tried so far:

const result = []
array.forEach((item, index, arr) => {
     if (item <= 350 && arr[index + 1] <= 350) {
          brokenMeasurements.push(item)
     }
})

I am struggling with identifying when the contiguous values end. Currently, this code only retrieves all values under 350.

Answer №1

To extract values from an array that are less than or equal to 350, you can iterate through the array and store these values in a temporary array. Once a value greater than 350 is encountered, the temporary array is pushed into the final result (if it contains more than one value) and then cleared. At the end of the iteration, if there are still values remaining in the temporary array, they are also added to the final result:

array = [500, 250, 380, 250, 230, 100, 700, 900, 200, 100, 10, 800, 5]

const result = []
var values = []
const l = array.length
for (let i = 0; i < l; i++) {
  v = array[i]
  if (v <= 350) {
    values.push(v)
  } else if (values.length) {
    if (values.length > 1) result.push(values);
    values = [];
  }
}
if (values.length > 1) result.push(values);

console.log(result)
// [[250, 230, 100], [200, 100, 10]]

Note that this code specifically adds sequences of values under 350 with more than one element to the final result. If you wish to include all sequences regardless of length, modify the condition:

values.length > 1

to simply

values.length

array = [500, 250, 380, 250, 230, 100, 700, 900, 200, 100, 10, 800, 5]

const result = []
var values = []
const l = array.length
for (let i = 0; i < l; i++) {
  v = array[i]
  if (v <= 350) {
    values.push(v)
  } else if (values.length) {
    result.push(values);
    values = [];
  }
}
if (values.length) result.push(values);

console.log(result)
// [[250], [250, 230, 100], [200, 100, 10], [5]]

Answer №2

var numbers = [500, 250, 380, 250, 230, 100, 700, 900, 200, 100, 10, 800, 5];
var output = [];
numbers.reduce((prev, current, index) => {
    if (current <= 350) {
        prev.push(current);
        if (index === numbers.length - 1) output.push(prev);
    }
    else {
        if (prev.length >= 1) output.push(prev);
        prev = [];
    }
    return prev;
}, []);
console.log(output)

Answer №3

Here is a code snippet you can experiment with:

const numbers = [500, 250, 380, 250, 230, 100, 700, 900, 200, 100, 10, 800]
let tempArray = []
const lessThan350 = numbers.reduce((result, num) => {
  if(num < 350) {
    tempArray.push(num)
  } else {
    result.push(tempArray)
    tempArray = []
  }
  return result
}, []).filter(element => element.length > 1)
console.log(lessThan350)

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

Using jQuery or JavaScript in an ASP.NET environment, you can make the parent list item of a dropdown link active

Welcome to my navigation menu <ul class="sidebar-menu" id="navigation-menu"> <li class="active"><a class="nav-link" href="/"><i class="fas fa-home"></i><span>Home Page</span></a></li> <li cl ...

"Discovering the method to access the most recent clicked event data across the entire JavaScript scope

function retrieve_data(){ var information = $(this).data(); // this is undefined console.log(information.crm); } $(document).on('click', '#add_info', (function() { var info = $(this).data(); // this works console.log(info.c ...

Challenges with creating a responsive YouTube iframe using the API

Looking to integrate a Youtube video using the iFrame API to capture events effectively, embedding the player alone is not an option. Following the documentation, everything functions correctly with code like: var tag = document.createElement('scrip ...

React video recording not displaying in the video element

I'm currently developing a React application that facilitates webcam interviews with candidates. As part of this process, candidates have the option to "Start Again" or "Complete" their interviews. One challenge I am facing is displaying the recorded ...

What causes the source code of a website to change when accessed from various browsers?

When analyzing the source code of bartzmall.pk using various browsers, it reveals different classes being added to the html tag for each browser. For Firefox: <html class="firefox firefox53 otherClasses"> For Chrome: <html class="webkit chrome ...

Fade Toggle fails to toggle properly

QUESTION: What could be the reason behind my fade in/fade out not functioning as expected? How can this issue be resolved effectively? BACKGROUND STORY: Upon clicking a link, a javascript/jQuery event is meant to display or hide a series of LI's. Pre ...

Vue Router - Checking if Paramater Exists in an Array

Looking for a solution: /browse/:type/:id? Is there a way to check if the value of :type is included in a predefined array of valid options? ...

Adjusting the Height of a Div Using a Single Button

Seeking help to make a div expand and then shrink with one button click. I've tried various methods but the div won't change size. Can someone guide me on why this is happening? Here is the code, CSS, and HTML for my latest attempt: $("dasButto ...

The Echart bar graph is not displaying when trying to use JSON data

Seeking assistance as a beginner in building Basic Bar inverted axes using json data. I am trying to achieve a chart similar to Bar Inverted Axes, but encountering issues with the chart not displaying properly. Utilizing Angular to develop the web applicat ...

What is the best approach to decipher an obfuscated JavaScript file?

While browsing a site, I came across a javascript file that appears like this: eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,Str ...

inquiry about using arrays in jQuery

Here is the code snippet I am working with: <script> $().ready(function() { $("#myVal#").blur(function() { var arr = jQuery.makeArray( $("#myArr").val() ) if ( $("#myVal").val().indexOf(arr) == -1 || $("#myVal").val().indexOf(arr) ==0) { a ...

To streamline your shopping experience, simply input various product IDs into the designated textbox to add multiple items to your shopping

I am currently working on a feature for Magento that allows customers to input multiple product IDs in a text box and add them to their shopping cart. I have successfully implemented this functionality for a single product ID using the jQuery code below: ...

How can I create a script in Discord.js that automatically sends users their information upon joining the server?

I'm currently working on developing a code that automatically sends the user's avatar, username, ID, account creation date, server join date, and status when they join The structure of the code looks something like this: module.exports = (Discor ...

slow loading background slideshow in css

Creating a simple slideshow for the background using CSS has been successful, but I am facing an issue with making all backgrounds utilize background-size: cover. I want the images to fit properly on the screen. Another problem is that the pictures take a ...

Receiving errors when sending XML via an AJAX request is a common issue

I'm encountering an issue with handling the response from a specific web service through my XML request. Despite the response appearing as expected in my browser's network tab, the error callback in my JavaScript code is triggering, treating it a ...

Creating dynamic 2-dimensional math matrices using malloc

While a similar question has been posed before, such as in this post: Malloc a 2D array in C I am interested in determining whether it is more advantageous to utilize a traditional 2D array structure (employing pointers of pointers) or if opting for a fl ...

Discovering and emphasizing formatted text with Angular: A step-by-step guide

I have recently been utilizing CKEditor, which is a feature-rich text editor that allows users to apply formatting such as "bold", "italic", "headings", "lists", and more. This tool converts the written message into HTML code with the appropriate HTML tag ...

React is unable to assign a class field beyond the scope of axios

class App extends React.Component { app: Application; ... componentDidMound() { axios.get(…).then(res => { this.app.currentUser = res.data.data; // setting value inside lambda function. console.log(this.app.currentUser); // ...

How can I locate and modify a particular cell within an HTML table using just JavaScript?

For my project, I am required to develop a functional shopping cart with a remove function. If an item is already in the cart, it should update the existing data when added again. Let's say I have the following items in my cart: Name: Quantity: Pric ...

The functionality of filtering a list based on the selected value from a drop-down menu is malfunctioning

When the page initially loads, there is a dropdown with the default placeholder "Select Person Type" and a checkbox list displaying all persons by default. An angular filter is used to display only the selected type of persons from the dropdown (working p ...