Rearranging an array using the numbers contained within the array elements in JavaScript

I'm currently working on unscrambling an array. The array contains string elements that are not in the correct order, with numbers attached to indicate their desired position. My goal is to extract these numbers from each item and rearrange them in a new array based on those numbers. For instance, let's take

var scrambled = ["pizza4", "to2", "I0", "eat3", "want1"]
. I already have a function that can locate and isolate these numbers within each item.

function unscramblePhrase() {
    var scrambled = ["pizza4", "to2", "I0", "eat3", "want1"];   
    var unscrambled = [];
    for (var counter = 0; counter < scrambled.length; counter++) {
        numPosition = scrambled[counter].search('[0-9]');
        arrayIndex = scrambled[counter].substring(numPosition);
        console.log(arrayIndex);
        unscrambled.push(scrambled[arrayIndex]);
    }
 console.log(unscrambled)
}

Currently, my approach of using the extracted numbers to reposition the elements in a new array is not yielding the desired outcome - instead of unscrambling, it just produces another scrambled array:

["want1", "I0", "pizza4", "eat3", "to2"]
.

Answer №1

The approach you're taking to sort the array may not be optimal. Instead of using Array.prototype.push, consider directly assigning the value to the desired index in the unscrambled array.

unscrambled[arrayIndex] = scrambled[counter];

Alternatively, you can utilize the Array.prototype.sort method

function getNum(str){
    return Number(str.substring(str.length -1));
}

unscrambled.sort((a, b) => getNum(a) - getNum(b));

Please note: The provided method sorts the array in-place. Depending on your requirements, this may or may not be desirable.

If needed, you can always apply this sorting operation on a clone of the array:

[...unscrambled].sort((a, b) => getNum(a) - getNum(b));

Answer №2

To simplify this process, you can utilize Regular Expressions (RegEx) to divide the array into value and index pairs, sort them accordingly, and then eliminate any extra information by using a secondary method like .map to return the string array.

scrambled.map(i => 
[i.replace(/\d/g,""), +i.replace(/\D/g,"")])
.sort((a, b) => a[1] - b[1])).map(i => i[0]);

var scrambled = ["pizza4", "to2", "I0", "eat3", "want1"];   

var unscrambled = scrambled.map(i => 
  [i.replace(/\d/g,""), +i.replace(/\D/g,"")])
  .sort((a, b) => a[1] - b[1])
  .map( i => i[0]);

console.log(unscrambled);

Answer №3

Give this a try, it might do the trick:

function descrambleWords() {
    var scrambled = ["apple4", "banana2", "orange0", "pear3", "grapes1"];<br>
    var descrambled = [];
    for (var count = 0; count < scrambled.length; count++) {
        numPos = scrambled[count].search('[0-9]');
        arrIndex = scrambled[count].substring(numPos);
        console.log(arrIndex);
        descrambled[arrIndex] = scrambled[count];
    }
 console.log(descrambled)
}

Answer №4

You may also try using the "Array.sort" method in this way:

var scrambledWords = ["pizza4", "to2", "I0", "eat3", "want1"]

let getNumberIndex = (word) => [...word].findIndex(letter => Number.isInteger(+letter))

let getNumber = (word) => word.slice(getNumberIndex(word))

let unscrambledWords = scrambledWords.slice(0).sort((a, b) => getNumber(a) - getNumber(b))

console.log(unscrambledWords)

Answer №5

let phrases = ["I0", "want1", "to2", "eat3", "pizza4"];

phrases
    .map(w => parseInt(w[--w.length]))
    .sort()
    .map(i => phrases.filter(w => w[--w.length] == i)[0].replace(i, ''));

// Result: ["I", "want", "to", "eat", "pizza"]

Answer №6

If you want to manipulate a string and index values using a single loop, here are two fun ways to do it:

var scrambled = ["pizza4", "to2", "I0", "eat3", "want1"],
    result = scrambled.reduce((r, string) => {
        var [s, i] = string.match(/\D+|\d+/g);
        r[i] = s;
        return r;
    }, []);
    
console.log(result);

Explore more exciting techniques with objects below!

var scrambled = ["pizza4", "to2", "I0", "eat3", "want1"],
    result = Object.assign(
        [],
        ...scrambled.map(s => (([v, k]) => ({ [k]: v }))(s.match(/\D+|\d+/g)))
    );
    
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

Incorporating Vue.js components into PHP applications

I am currently working on a project using PHP in conjunction with Vue.js and vue-router. In my PHP form handler, I have implemented functionality to send emails. What I am trying to achieve is redirecting the user to a specific component within my Vue ap ...

Comparison between referencing the DOM and storing references to the DOM elements

Can you explain the contrast between these two statements? $("#txt").val("123"); versus var txt=$("#txt"); txt.val("123"); Which statement is considered more effective in terms of efficiency? ...

Step-by-step guide on building an admin dashboard for your React application

Recently, I built an online store website using React. Currently, the data is being loaded from a local .json file. However, I am in need of creating an admin panel to allow the site administrator to manage and update cards and data on their own. Is there ...

"Vanishing Act: Google Maps Markers in React Mysteriously Disappear upon

Struggling with the react-google-maps module, particularly when it comes to markers and component re-rendering. Here's the issue: Initially load page with map and a few markers (all good) Click on a tab in the nav-bar -> page switches content in ...

Warning: Typescript is unable to locate the specified module, which may result

When it comes to importing an Icon, the following code is what I am currently using: import Icon from "!svg-react-loader?name=Icon!../images/svg/item-thumbnail.svg" When working in Visual Studio Code 1.25.1, a warning from tslint appears: [ts] Cannot ...

Count of daily features in JavaScript

Suppose there is a json document structured as follows: { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "time": 1438342780, "title": "Iran's foreign minister calls for world's ...

What is the best way to use ajax to send a specific input value to a database from a pool of multiple input values

Welcome everyone! I'm diving into the world of creating a simple inventory ordering site, but am facing a roadblock with a particular issue: Imagine you have a certain number (n) of items in your inventory. Based on this number, I want to run a &apos ...

What is the inner workings behind server side rendering in Next.js?

I am seeking clarification on Server Side Rendering, specifically with Next.js. During server side rendering, I want to confirm the 'execution path' as follows: Client makes a request to the server for the webpage, which serves up an HTML only ...

Navigating through JQuery

Is there a way to scroll to a div + 100px specifically on the y axis? I am unsure how to achieve this. Can you provide guidance? I attempted using $.scrollTo('div100' + '100px', 2000) but unfortunately, it did not produce the desired ...

Sending data to the template

Currently, I am working with NodeJS/Expressjs and have implemented the following route: router.post({ var value = req.body.value; //I NEED TO DO SOMETHING LIKE var file = '../test/test.js'; file.render(value); }); The content of / ...

Reset IntersectionObserverAPI to its initial state when none of the elements are in view

Currently, I am utilizing a React Hook that enables me to observe when an element becomes visible in the viewport. The functionality works smoothly until I encounter the need to 'reset' the state once all elements are hidden (such as when reachin ...

Steps for adjusting button size in Sencha Touch

How can I resize a button in Sencha Touch 2 to make it smaller? I need to change its height. Any sample code you could provide would be greatly appreciated! Thanks navigationBar: { items:[{ xtype: 'button', ...

Save JSON Tree data in the Database

Given a tree structure JSON, I am tasked with creating an API to insert all the data into a database at once. The organization entities can have multiple parents and children relationships. An example of the JSON data: { "org_name": "orga ...

Guide on Redirecting Response to a File using Co-Request module with NodeJs

I am utilizing Co-Request from this repository to fetch a Zip file from a URL, and the code I have for fetching it is as follows: The current code works fine. However, I'm facing difficulty in saving the response Zip file to an actual file. var co = ...

What is the process for changing colors once vertex colors have been updated?

Explaining the issue with an example. I have included a brief snippet of HTML code here to demonstrate the problem. In this scenario, I have created a simple triangle geometry as a global variable. By clicking the "Red" button, function red() is invoked ...

Issue: React does not allow objects as children for rendering. (You have provided an object with keys {user})

Currently in the process of implementing the authentication flow for my app utilizing the context API const AuthContext = createContext({}); export const AuthProvider = ({ children }) => { return ( <AuthContext.Provider value={{ user: " ...

Utilizing Conditional Styling for an Array of Objects within a Textarea in Angular 6

My array contains objects structured as follows: list =[ { name:"name1", value:true } { name:"name2", value:false } { name:"name3", value:true } { name:"name4", value:false ...

Add a picture and adjust its size as needed

Currently facing an issue where I am attempting to upload an image and display it on screen in a draggable and resizable manner. Utilizing jquery for the draggable and resizable functionalities, the problem lies in the fact that the draggable function is f ...

How can I update the gradient color upon refreshing the page while ensuring the cursor remains on the same

I have managed to get the cursor position and gradient working, but I'm struggling to make the gradient color change dynamically while still maintaining the functionality of the cursor position element. My goal is to have the gradient color change ev ...

I keep encountering errors with TypeGuard

Looking for some guidance with typescript. Even after implementing a type guard (and including the '?' symbol), I'm still encountering errors in the code snippet below. Is the syntax correct or should I make changes to the tsconfig file? int ...