Locating the index of a specific number within an array

Given an array of numbers like this:

let numbers = [4,7,2,0,9];

I would like to map the numbers in the array based on their size and return their positions. The expected output should be:

numbers = [3,4,2,1,5];

Thank you!

Answer №1

This solution is the most straightforward one among all the answers provided

For smaller arrays, this method will work effectively. However, for larger arrays, it is recommended to use a lookup Map for better performance.

const arr = [4,7,2,0,9]

const indices = arr.slice(0).sort((a,b) => a-b); // make a sorted copy of array
const result = arr.map(item => indices.indexOf(item)+1); // map indices plus 1

console.log(result)

Answer №2

Replicate the array, arrange it in ascending order, and pair each number with its index + 1. Transform the pairs into an object called position.

Next, iterate through the original array and fetch the position of each number from the positions object.

const numbers = [4,7,2,0,9];

const positions = Object.fromEntries(
  [...numbers]
    .sort((a, b) => a - b)
    .map((num, index) => [num, index + 1])
);

const result = numbers.map(num => positions[num]);

console.log(result);

You can utilize a Map instead of an object by substituting Object.fromEntries() with the constructor of Map:

const numbers = [4,7,2,0,9];

const positions = new Map(
  [...numbers]
    .sort((a, b) => a - b)
    .map((num, index) => [num, index + 1])
);

const result = numbers.map(num => positions.get(num));

console.log(result);

To handle numerous identical values, condense the array into a Map and incorporate the current index. While iterating through the initial array, extract the index of the value from the beginning of each entry's value:

const numbers = [1, 2, 1, 0, 0, 0];

const positions = [...numbers]
  .sort((a, b) => a - b)
  .reduce((acc, v, i) => acc.set(v, [...acc.get(v) ?? [], i + 1]), new Map())

const result = numbers.map(num => positions.get(num).shift());

console.log(result);

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

Teaching you the best way to incorporate numeral.js from app.locals into the script section of my jade file

Encountering issues while trying to utilize numeral.js within the script section of my jade file. Here is how I have numeral placed in locals: app.locals.numeral = require('numeral'); However, when I attempt to use numeral on a variable in my ...

Grails 3 - Resource Management Extension

Can anyone recommend a great Grails plugin for the latest version of Grails 3 (specifically working with 3.0.4)? I'm looking for something like this one () that allows me to create resource bundles for JS, CSS, and other dependencies. I think having ...

As two divs glide across the screen, the top div remains hidden from view

To enhance our user experience, we are tasked with creating a captivating screen saver featuring 3 images. The bottom image will remain fixed in its position. The middle image should move across the screen. Lastly, the top image will move at a faster ...

Tips for utilizing sendToDevice multiple times in a function return value

In my Firebase Cloud Functions script, I have successfully implemented sending push notifications to users using a specified set of token arrays returned by a function: return getTokens(array1).then(tokens => { return (admin.messaging().sendToDevice( ...

NodeJS Code Snippets for Natural Language Processing

In my NodeJS application, I am utilizing the talkify library to create a chatbot that can process code snippets of a closed-source language. These snippets are processed through a REST API and the result is returned by the bot. While I have successfully i ...

Utilizing D3 for translation by incorporating data from an array within d3.js

I need assistance with drawing rectangles in an SVG where the translation data is stored in an array. Below is the code: var vis=d3.select("#usvg"); var rectData=[10,21,32,43,54,65,76,87,98,109]; vis.selectAll("rect").data(rectData).enter().append("rect ...

The file_get_contents() function encountered an issue as the content type was not specified, leading to it assuming

I am currently working on a project using PHP and JavaScript. I need to call an API from the camera using PHP code. I am using the file_get_contents function and Post request for this purpose. Below is the code snippet: $value = $_POST['TakeNewPic&ap ...

Tips for displaying the content of a personalized navigation tab using jQuery

I successfully created custom tabs using JQuery. Here is the code for my custom tabs: <div class="row"> <div class="col-4 master-advanced-left-tab master-advanced-left-tab-active"> <p>Item 1</p> </div> < ...

"Encountering difficulties in utilizing the Chrome message passing API through Selenium's execute_script function

Currently, I am trying to send a value to a chrome extension from a browser automation script by invoking the chrome.runtime.sendMessage API from Selenium. Below is the python code I am using: import os import time from selenium import webdriver from sele ...

AngularJS version 1.3 faces issues with updating bindings when a controller without $scope retrieves data from a webapi

After checking out the link provided below, I noticed that in Angular 1.3 they advise against using '$scope.x' inside the controller and instead suggest using 'this.x' https://docs.angularjs.org/api/ng/directive/ngController The issue ...

Can a single endpoint be used to provide files to web browsers and data to REST requests simultaneously?

I recently completed a tutorial that lasted 7 hours on creating a blog, following it almost completely. The only step I skipped was setting up separate client/server hosting as suggested in the tutorial. Instead, I have a single Heroku server serving the c ...

Sharing data between parent and child components in React

I am facing an issue with passing a dynamically generated value from child components to my parent/web component. The buttons in the child component are assigned a `value="URL"` based on MongoDB data, and I want to pass that value to my parent component us ...

The functionality of Jquery Ajax is limited to a single use

I'm having an issue with a page that is supposed to reload the data within a div using jQuery, but it only updates once. Here's a snippet of my code: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0 ...

Automatically adjust the size of embedded video streams within DIV elements

My application is quite simple, it displays four video streams in a quadrant layout. Users can double click on each video to switch to full-screen mode and then again to go back to the quadrant view, which all works perfectly. The issue I'm facing in ...

The YYYY-dd-mm input mask pattern is malfunctioning

Hello, I am having trouble creating a pattern for an input field in the format YYYY-mm-dd. My code is not working properly. Can someone please help me correct my code? Any assistance would be greatly appreciated. <html> <head> <title>En ...

Express removes newlines while reading buffers and sends them back in the response

When processing a GET request, I am taking a file and converting it into a string using the toString() method before sending it back to the client: new Promise((resolve, reject) => { fs.stat(filepath, (err, stats) => { if (err) { reject( ...

The ref.on() method fails to trigger a response from a function, despite producing the intended outcome

I've been working on developing an app called workspace. I previously asked a question, but I've made more additions to the features now. One of the new features is a remarks system. After experimenting with different versions of my code, the ver ...

Retrieve the form data in real-time using JavaScript immediately after submitting the form, all before the page even has a

I have utilized Django for creating a web application. Once the form is submitted, I aim to retrieve the processing result (in this case, "msg") instantly within the view function, without waiting for a page refresh. urls.py: path('index/', view ...

The process of dynamically inserting input types into a <td> element using the innerHTML tag is not functioning properly in Internet Explorer

I am facing an issue with dynamically placing input types within a <td> tag - the innerHTML() method is not functioning properly in Internet Explorer, although it works fine in Mozilla. This is how I am inserting the input types using JavaScript, wi ...

`Exit out of the current tab and navigate back to the parent tab`

Looking to add a link on a webpage that will specifically close the active tab in a browser without affecting other tabs. Upon clicking the close link, the user should receive an alert message prompting them to confirm with two options: "YES" and "NO". If ...