Tips for showing the previous value associated with a specified value in an array using JavaScript

Is it possible to retrieve the previous value of a given input from an array? If so, how can we achieve this?

var theArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 14, 15];
const findValue = (arr, input) => {
  // To do
}
findValue(theArray, 15)

If we provide the input as 15, the expected output is 14.

Answer №1

To uncover the position of the given input within an array, and subsequently reveal the index preceding it:

var numArray = [1,2,3,4,5,6,7,8,9,14,15];
const findPreviousValue = (arr, target) => arr[arr.indexOf(target) - 1]
console.log(findPreviousValue(numArray , 15))

It's advisable to account for scenarios where the input falls at index 0...

Answer №2

function searchForPreviousValue(array, target) {
  let previousIndex = array.findIndex(element => element === target) - 1;
  return previousIndex < 0 ? null : array[previousIndex];
}

If there is no previous item in the array, this function will return null and it searches from left to right.

Answer №3

Assuming the value is one-of-a-kind, conveniently locate it within the array by employing a recognized search method such as binary search. Once found, retrieve the index that precedes this value (unless it happens to be the initial entry).

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

Guide on displaying a document in react-doc-viewer from a protected API endpoint in either Next.Js or ReactJs

I am looking to display files in my Next.JS web application using a secure API. The API provides the following data: { "name": "Test1.docx", "contentUri": "https://api.mypurecloud.ie/api/v2/downloads/x ...

What is the most effective way to incorporate the DOMContentloaded event listener into the document using nextJS?

I am working on integrating an HTML code snippet into my Next.js project. The snippet includes an external script with a createButton function. <div id="examplebtn"></div> <script type="text/javascript"> //<![ ...

jQuery functions smoothly on Firefox, but encountering issues on Chrome

While it may seem like a repetitive inquiry, I have thoroughly researched similar questions and have not found a suitable solution. The server is returning the following response through a standard ajax call: <form id="ctl00" name="ctl00" method="post ...

Is your script tag not functioning properly with Promises?

Below is the code snippet used to dynamically append scripts in the DOM using promises. This piece of code is executed within an iframe for A-frame technology and it is generated using Google Blockly (Block-based coding). export const appendScript = asy ...

Is there a way to modify the colors of particles in GPUParticleSystem with Three.js?

I have encountered an issue where I am trying to add black particles in a white THREE.scene. Despite changing the spawn option color, there are still white particles present as if there is a base particle spawn color. The problem arises when I set a white ...

How can I initiate a button click event in aspx by pressing the "Enter" key on a textbox, with the button click event being defined in the source cs file?

I am trying to trigger the btnSearchSuiteGroup_Click event when the "enter" key is pressed on the txtSuiteGroupName textbox in the aspx file. Below is the code snippet: <asp:TextBox ID="txtSuiteGroupName" runat="server" clientidmode="Static" CssClass=" ...

Display the top 10 highest numerical array elements in PHP

Every time a new 'item' is added to my website, I record the item number in a file named items_added.log. The objective now is to create a script that displays the 5 most frequently added items. Consider this array: 1 => 100 2 => 200 3 =&g ...

"Expand your list in AngularJS by automatically adding more items if the ng-repeat count is

I am struggling with this section of code. It currently shows a box with the first four linked resource images. However, I need it to display additional images if there are less than four. I tried looking for a solution, but couldn't find one. <di ...

The Bootstrap carousel is stuck and not moving

I'm really struggling to figure out why the bootstrap carousel code isn't working for me. It's frustrating because I followed the example on the bootstrap website and only made minor customizations, so it should be functioning properly. I su ...

Dropdown selection returning the text value instead of the designated value

Is it possible to retrieve the text "Region 1" instead of just the value '1' from a dropdown menu in PHP? <select name = 'region' id = 'region'> <option value = '1'>Region 1</option> <select&g ...

Customizing Magnific Popup: Changing showCloseBtn and closeOnBgClick settings during display

Is there a way to customize the behavior of an open instance of a magnific popup? I want to have different settings for when the popup is closable and when it should be prevented from closing. It appears that these options are only available during initial ...

Browsing through tabs to locate specific text

Currently, I am developing a feature for a Chrome extension and I could use some assistance in debugging. The feature involves retrieving a user's input as a string from a text box on popup.html and then scanning through all the open tabs in the curr ...

Steps to store chosen option from dropdown list into a database's table

I am currently populating a dropdown list in my PHP file by fetching data from a database. Here is the code snippet: <script type="text/JavaScript"> //get a reference to the select element var $select = $('#bananas'); //reques ...

One way to incorporate if / else if statements into a function within a Class component is by using conditional logic in React alongside Node and Express

I'm looking to refactor my code and extract the if/else if statements for error handling out of the component. How can I export this logic to another file and then import it back into my main component? Here's an example of the code: // PASSWOR ...

Is it possible for me to pass a reference to a specific object's instance function?

Can JavaScript allow you to pass a function reference to a specific object's function, similar to what can be done in Java? Let's take a look at this code snippet: _.every(aS, function (value) { return exp.test(value); }); What if we want ...

Toggle the submit button using jQuery based on the comparison of the jml_automatic field with the id_km field

I recently learned jQuery last month, and now I am working on a form using jQuery to allow users to input gas requests. However, the script is not working to compare the values from #jml_km with #id_km, and the submit button is still not disabled when the ...

Need to know how to show a DIV for a specific time frame using Javascript?

One of the features I am looking to implement in my Django application is a display that notifies the user when one of their posts is about to start. The idea is to show a DIV element with the message: <div>“Will start soon”</div>, 15 minut ...

Limit the use of Javascript specifically within a section of HTML that includes a rich-text editor

Currently, I am working on a web application that has a historic background. This application uses the summernote editor, a rich-text editor that allows users to save formatted notes to the server. Along with this, there are numerous instances of inline Ja ...

Interacting between React and Express with CKEditor 5: How to send a request

import React, { Component, useState, useEffect } from 'react'; import { CKEditor } from '@ckeditor/ckeditor5-react'; import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; import axios from 'axios'; import pa ...

Unable to populate an array with a JSON object using Angular framework

Here is the JSON object I have: Object { JP: "JAPAN", PAK: "PAKISTAN", IND: "INDIA", AUS: "AUSTRALIA" } This JSON data was retrieved as a response from an HTTP GET request using HttpClient in Angular. Now, I want to populate this data into the following ...