Sorting an array, adding a value to it, and finding the lowest index

I'm currently tackling a JavaScript challenge that requires writing a function to determine the lowest index at which a value (second argument) should be inserted into a sorted array (first argument). For instance, if we call where([1,2,3,4], 1.5), the expected output is 1 because 1.5 falls between 1 (0th index) and 2 (1st index).

The provided hint suggests utilizing the built-in ".sort()" method, with which I am somewhat unfamiliar prior to this challenge. Below is my attempt so far, although I suspect it's quite off-track.

function where(arr, num) {
  arr.push(num).sort(function(a,b){return a-b;});
  return arr.indexOf(num);
}

console.log(where([40, 60], 50)); // outputs "unexpected identifier"

Answer №1

Separate the following sentences.

function findIndex(arr, target) {
  arr.push(target);
  arr.sort(function(x, y) {
    return x - y;
  });
  return arr.indexOf(target);
}

console.log(findIndex([30, 50], 20)); // 0
console.log(findIndex([30, 50], 40)); // 1
console.log(findIndex([30, 50], 60)); // 2

Answer №2

According to @Xufox, it's important to note that push in JavaScript returns the new length of the array and not the array itself.

To improve your code organization, consider rearranging it like this:

function where(arr, num) {
  arr.push(num); // Add 'num' to array.
  arr.sort(function(a,b){return a-b;}); // Sort the array. 
  return arr.indexOf(num); // Find index of 'num'.
}

console.log(where([40, 60], 50));

Answer №3

const findIndex = (array, value) => {
  const sortedArray = array.sort((a, b) => a - b);
  const index = sortedArray.find(item => value <= item);

  return index === undefined ? array.length : array.indexOf(index);
}

Answer №4

const findIndexToInsert = (arr, num) => {  
  arr.sort((a, b) => a - b);
  let index = 0;
  while(num > arr[index]){
    index++;
  }
 return index;
}

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

Adding arrays to a larger array

<?php $images =[]; $imagesArrays = []; //Querying the database for image galleries $loop = new WP_Query( array( 'post_type' => 'gallery', 'posts_per_page' => 100 ) ); while ( $loop->have_po ...

Navigating JSONP using jQuery

I'm encountering an issue where I can see the correct response in Firebug, but I'm unable to access the data it returns. I need some guidance on how to achieve this. Specifically, I'm attempting to place the timestamp of an entry into a div ...

Unveiling Insights from a JSON File: Data Extraction

I have a JSON file named pio2.json that contains the following data: { "controles":[{ "chart":[{ "type":"columns", "title":"Pollitos" }], "datos":[{"key":"Math","value":98}, {"key":"Physics" ...

What steps can I take to display a download button when a file is clicked on?

As a backend developer, I usually don't delve into JavaScript tasks, but I have a simple query for JavaScript developers that I need help with. Here is my question: I am trying to display a download button when a specific file is clicked using jQuery ...

Set a variable to represent a color for the background styling in CSS

My goal is to create an application that allows users to change the background color of a button and then copy the CSS code with the new background color from the <style> tags. To achieve this, I am utilizing a color picker tool from . I believe I ...

Explore the Filter List without being affected by the arrangement of words or the level of search precision

I was able to resolve the issue by adjusting my search filter algorithm. Now, I can search regardless of word order, but the results are not as specific as I need them to be. When I type "Correy" in the search bar, it shows all results containing that wo ...

Creating a Timeout Function for Mobile Browsers in JavaScript/PHP

Currently, I am developing a mobile-based web application that heavily relies on AJAX and Javascript. The process involves users logging in through a login page, sending the data via post to the main page where it undergoes a mySQL query for validation. If ...

Error encountered while attempting to execute Typescript with tsc file.ts in the WebGL2RenderingContext

After successfully installing Typescript using both npm and yarn on my Windows 10 machine, I encountered an error when trying to run 'tsc file.ts'. The error message reads '582 declare var WebGL2RenderingContext'. The error traceback p ...

Assigning names to the points on the AxisHelper component in THREE.js

Take a look at the code snippet provided below: <html> <head> <title>My first Three.js app</title> <style>canvas { width: 100%; height: 100% }</style> </head> <body ...

Is it possible to utilize the AmMap API for developing an Android application?

I am currently in the process of creating a unique application with HTML, JS, and jQuery Mobile that will feature interactive maps. I have been searching the web for APIs to incorporate interactive maps into my project without using Google Maps APIs when I ...

PHP - WebCalendar - Show or Hide Field According to Selected Item in Dropdown List

Working with the WebCalendar app found at to make some personalized adjustments to how extra fields function. I've set up two additional fields: one is a dropdown list of counties, and the other is a text field. Within the dropdown list, there is an ...

Update a div in PHP using the data received from an AJAX response

I recently developed a PHP application and encountered an issue with updating the value of a date picker. The user is prompted for confirmation when changing the date, and upon confirmation, the date in the "expiry" field (with id expiry) should update alo ...

Exchanging elements in a two- dimensional array

Presenting my implementation of the FCFS algorithm. I am working with a two-dimensional array named atst, which represents arrival time and service time. The dimensions of the array are 5*5. Visual representation of my array: First column: process name ...

Accessing an object from an AngularJS controller in an external function

I previously inquired about this issue and received a suggestion to add a service, but it did not solve the problem. I am trying to access a variable from a controller ($scope) within an external function. Below is a snippet of the example: app.controll ...

In Javascript, merge two arrays together in a specific format

Can we transform two arrays into a specific format so I can create my D3 graph? Here are the two arrays I have: date = ["sept,09 2015","sept, 10 2015","sept, 11 2015"] likes = [2,4,5] I need to convert them to this format: [{ date: '...', lik ...

Is it possible to have Mobile WebKit store the click position?

I am in the process of developing a unique framework specifically designed for WebKit devices. One of the features I have implemented is a series of list views that activate a 'hover' class when users touch them. Below is the jQuery/JavaScript co ...

The chatbot text input feature is malfunctioning and failing to display the entered text in the chatbox

Hi there! I'm in the process of creating a chatbot using a basic input text box and button in HTML, with a php start function. Unfortunately, when I enter text into the textbox, nothing is showing up on the screen and the button doesn't seem to b ...

Having trouble retrieving the API URL id from a different API data source

For a small React project I was working on, I encountered a scenario where I needed to utilize an ID from one API call in subsequent API calls. Although I had access to the data from the initial call, I struggled with incorporating it into the second call. ...

Can I assign a custom form id before manually triggering submission using AJAX?

I have developed an interesting code snippet that uses AJAX to submit a form only if the form has an ID attached to it. $(document).delegate('form', 'submit', function(event) { var $form = $(this); var id = $form.attr('id& ...

Modifying the attribute of an element inside an array

Presented below is an object: { "_id" : ObjectId("5a8d83d5d5048f1c9ae877a8"), "websites" : [ "", "", "" ], "keys" : [ { "_id" : ObjectId("5a8d83d5d5048f1c9ae877af"), "name ...