Discovering which elements in a numeric array are larger than the preceding elements

array: const numbers = [158,164,742,99,155,250,240,87]

To display in the console only those numbers that are greater than the previous ones: console.log(164 742 155 250)

const numbers = [158, 164, 742, 99, 155, 250, 240, 87]
function findBiggerNumbers(numbers) {
  for (let i = 1; i < -1; i++) {
    if (numbers[i] > numbers[i - 1]) console.log(numbers[i])
  }
}

What is the solution to this problem? Appreciate any help.

Answer №1

Employ .flatMap() and compare the current values with future values:

x < a[i+1] ? a[i+1] : []

I have noticed that there seems to be limited utility for using .flatMap() as a filter.

Therefore, why not opt for .map() instead of .flatMap()? Since .flatMap() essentially serves as an equivalent but with an additional step? This supplementary step enables me to devise a more straightforward logic where I can utilize simpler algorithms without having to concern myself with common side effects associated with handling arrays, such as obtaining empties. Here's a comparison between example #1 using .flatMap() and another version utilizing .map().

const data = [158, 164, 742, 99, 155, 250, 240, 87];

let resA = data.flatMap((x, i, a) => x < a[i + 1] ? a[i + 1] : []);

console.log(resA);

let resB = data.map((x, i, a) => x < a[i + 1] ? a[i + 1] : '');

console.log(resB);

Both .map() and .flatMap() necessitate returning data after each iteration, yet due to .flatMap() containing a built-in .flat() method, it allows for returning an empty array that equates to nothing, which is superior to returning an empty string ('') or undefined.

What about using .filter(), which undeniably appears to be the most straightforward solution? Let's compare Vectorjohn's callback here with my callback:

i > 0 && x > a[i - 1] // Vectorjohn, employing .filter()

x < a[i + 1] ? a[i + 1] : [] // My approach, utilizing .flatMap()

When utilizing .filter(), there is typically no need to worry about overshooting zero and triggering a return of

undefined</code, since <code>.filter()
solely returns truthy data and never falsey data. Hence, his callback might simply be the reverse of my callback by eliminating i > 0 &&:

x > a[i - 1] // .filter() will return x

x < a[i + 1] ? a[i + 1] : [] // .flatMap() will yield a[i + 1]

My approach doesn't automatically remove undefined, making it slightly more verbose than Vj's (once corrected). However, .flatMap() offers far greater versatility compared to .filter(). While .filter() consistently returns the current value (x) on each iteration, .flatMap() has the ability to yield anything (a[i + 1]), multiple items (["any", x]), or nothing ([]) during each iteration.

Illustrative Example 1

const data = [158, 164, 742, 99, 155, 250, 240, 87];

let res = data.flatMap((x, i, a) => x < a[i + 1] ? a[i + 1] : []);

console.log(res);

Answer №2

When using the array filter method, a function is executed for each element in the array. Only elements that return true from the function are included in the final result. The current element's index is passed as an argument to the function, allowing you to access the previous element within your filter logic.

data.filter((value, i) => i > 0 && value > data[i - 1])

filter can also take the original array as a third argument, which can be useful for making the filter callback more reusable:

const biggerThanPrevious = (value, i, array) => i > 0 && value > array[i - 1]
// ... elsewhere in the code
const data = [158,164,742,99,155,250,240,87]
console.log(data.filter(biggerThanPrevious))

Answer №3

You were so close to getting it right with your forloop.

IMPORTANT: Avoid using negative values in your loops unless specifically needed to iterate backwards.

const numbers = [158, 164, 742, 99, 155, 250, 240, 87];
var result = [];
for(let i = 0; i < numbers.length; i++){
  if(numbers[i] > numbers[i - 1]){
    result.push(numbers[i]);
  }
}

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №4

const dataSet = [158, 164, 742, 99, 155, 250, 240, 87]

let outputNumbers = ''

dataSet.forEach(num => {
  const indx = dataSet.indexOf(num)

  if (num > dataSet[indx - 1]) {
    outputNumbers += `${num} `
    // you may also simply log the number using console.log(num), but I prefer to append to a string
  } 
})

console.log(outputNumbers)

Answer №5

This situation seems like a perfect fit for utilizing Array.prototype.reduce().

Set the second parameter of the reduce function (the accumulator/carry value) as an object with two keys that represent the resulting array and the value from the previous iteration.

let data = [158, 164, 742, 99, 155, 250, 240, 87];

let result = data.reduce(function(accumulator, currValue) {
  if (currValue > accumulator.lastValue) {
    accumulator.greaterThanPrev.push(currValue);
  }
  accumulator.lastValue = currValue;
  return accumulator;

}, {
  greaterThanPrev: [],
  lastValue: 4294967295 // BACK-COMPAT. MAX INT.
});

console.log(result.greaterThanPrev)

In each iteration, compare the current value with the 'lastValue' in the object passed through the reduce function. If it's larger, add it to the 'greaterThanPrev' array and update the 'lastValue'. Return this updated object for the next iteration. Once the reduce function completes, the final object will contain all the desired values in 'greaterThanPrev'.

There might be cleaner solutions out there, but this one came to mind quickly.

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

Sophisticated filtration mechanism involving two entities and a binary condition

I have an array called burgerActions : [ { statusId: 2, label: 'Accept' }, { statusId: 3, label: 'Reject' }, { label: 'Consult' }, { label: 'Transfer' } ] and also this objec ...

Does combineLatest detach this from an angular service function?

Check out this test service on Stackblitz! It utilizes the combineLatest method inside the constructor to invoke a service method: constructor() { console.log("TEST SERVICE CONSTRUCTED") this.setParameters.bind(this) this.assignFixedParamete ...

When attempting to add objects to an indexedDB object store, an InvalidStateError is encountered

I have defined IndexedDB and IDBTransaction dbVersion = 1; var db; var dbreq; var customerData = { ssn: "444", name: "Bill", age: 35, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b0bbbebe92b1bdbfa2b3bcabfcb1bdbf"& ...

Is there a way to retrieve a jQuery element from a regular JavaScript selection?

When a user selects text on my page, I pass the selected object to a function. In this function, I need to retrieve the appropriate text note using jQuery. How can I accomplish this? Here is the function: var manipulator = function (coreObject) { con ...

Show the percentage of completion on the progress bar while uploading with AJAX

I'm having trouble updating the current upload value on my progress bar in real-time. I know how to do it when the progress bar has stopped, but I can't get it to update continuously. xhr.upload.onprogress = function(e) { if (e.lengthComputa ...

Sending a variable to the resize() function in jQuery

Currently, I am working with two specific divs in my project: "#sidebar-wrapper" and ".j1". The height of ".j1" is dynamic as it changes based on its content. My objective is to set this height value to the "#sidebar-wrapper" element. I have attempted to ...

Guidelines for adjusting the next/image component to a full 100% height

In my Next.js application, I am trying to display an image that fills the full height of its container while automatically adjusting its width based on its aspect ratio. I attempted the following method: <Image src="/deco.svg" alt=&qu ...

Unable to execute simple demo on the threejs.org platform

As I delve into learning three.js, I came across some examples worth exploring. One specific code snippet I attempted to execute can be found here. Unfortunately, all I saw was a blank black screen. To troubleshoot, I adjusted the three.js source to my lo ...

Issues arose when attempting to navigate in a JavaScript handler within ASP.NET MVC

As a newcomer to Javascript, I hope my question isn't too basic. I have a button in my ASP.NET MVC 4 view: <input name="button" type="button" id="button1" value="Click me1"/> In order to create a click handler for the button, I've added ...

Remove an item from a JSON Array

I've been struggling to extract a specific object from a JSON query. Despite spending hours searching for a solution, I can't seem to figure out how to retrieve the URL from the Blogs response. The challenge lies in navigating through the array s ...

The Flot chart is experiencing difficulties displaying time and count data

Hello, I am currently working on creating a flot graph and I have been using this plugin found at . My goal is to display time (h:m) on the x-axis and counts on the y-axis. I have written a script for this purpose, but unfortunately, it's not functio ...

Implementing server authentication with Faye in Node.js

As a complete newbie to node.js and faye, I'm struggling with the basics and not sure what questions to ask. This is how my faye server setup looks like, running on Nodejitsu: var http = require('http'), faye = require('faye' ...

The Vuejs component finds itself unable to retrieve its own data

Main Component: <template> <spelling-quiz v-bind:quiz="quiz"></spelling-quiz> </template> <script> var quiz = { text: "blah:, questions: ['blah blah'] } import spellingQuiz1 from & ...

Issues have been observed with the keyframe animation involving a JavaScript timer, specifically in the rotation of the outer circle around the inner circle

I seem to be encountering an issue with an animation. My goal is to have three arrows in a circle that rotate around an inner circle and pause every 3 seconds for another 3 seconds before continuing to rotate. However, instead of rotating smoothly, the ani ...

Ways to conceal a column within columnSelection

Can anyone help me with setting the Column selection for Sender and Receiver in bootgrid without including Id in the column selection dropdown? I need some guidance on how to achieve this. Check out the image below for reference https://i.sstatic.net/4EEW ...

What specific bower package is required for implementing the locationProvider functionality in AngularJS?

I've been attempting to remove the hash tag from my URL in AngularJS. After some research, I discovered that I need to use $locationProvider, but I'm unsure which dependency is required to make this work. This is my Angular code: angular.module ...

Encountering an unforeseen change in the "buttonText" attribute

I've developed a simple Vue.js component for a button. When the button is clicked, it should display the text "I have been clicked." It does work as expected, but I'm also encountering an error that reads: 49:7 error Unexpected mutation of "but ...

Navigating through items and organizing based on several criteria

In JavaScript, I am currently learning about accessing objects and sorting them based on multiple conditions. As a beginner in JavaScript, this may seem like a very basic question to some. My task involves sorting based on the 'status' field. va ...

Transferring the output of a function to a different state

My current challenge involves sending data from one controller to another within an Ionic application. Despite creating a service for this purpose, I am still unable to share the data successfully. The send() function in MainCtrl is meant to pass the data ...

Utilizing Node, ObjectionJS, and Knex, we can establish a one-to-many relationship and retrieve the first associated row from the many

To simplify, I use two tables for a chatbox: Conversation and Message Conversations ID Status 1 open 2 open Messages Conversation ID Text Date 1 'ffff' (random date) 1 'asdf' (random date) 1 '3123123123&ap ...