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!
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!
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)
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);
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 ...
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 ...
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 ...
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( ...
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 ...
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 ...
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 ...
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> < ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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( ...
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 ...
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 ...
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 ...
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 ...