The error "Cannot invoke the indexOf method on an undefined element at order" is being encountered in Javascript

Looking for assistance with creating a function to sort a string where each word contains a single number from 1 to 9 (no 0).

For instance, given the input: "is2 Thi1s T4est 3a", the desired output should be "Thi1s is2 3a T4est".

The current code snippet:

function order(words)
{
    // ...

    if(words === '')
    {
        return words;
    }

    var all_words = words.split(" ");
    var checked_words = new Array(); 
    var joined_words = "";

    for(i = 1; i <= 9; i++)
    {
        //console.log(checked_words);
        //checked_words[i-1] = all_words;
        for(j = 1;j <= all_words.length; j++)
        {
            if(all_words[i-1].indexOf(i) !== -1)
            {
                checked_words.push(all_words[i-1]);

                if(i == (all_words.length))
                {
                    joined_words = checked_words.join(" ");
                    return joined_words;
                }
            }
        }
    }
}

Encountering an issue of "TypeError: Cannot call method 'indexOf' of undefined at order." Any help would be greatly appreciated. Thank you!

Answer №1

After some investigation, I've finally come to understand the purpose of that initial loop - it's scanning for numbers within the string. However, this method is not recommended due to its peculiar nature and lack of efficiency if it actually functions as intended.

Instead, a more optimized approach would involve utilizing a single loop in conjunction with a regex pattern to identify the numbers within the string.

for (var i = 0; i < all_words.length; i++) {

  // locate the first matching number and convert it to an integer
  var n = +all_words[i].match(/\d+/)[0];
  checked_words[n] = all_words[i];
}

// The 'checked_words' array contains an undefined element at index 0;
// using slice creates a duplicate of the array starting from index 1
return checked_words.slice(1).join(' ');

Check out the DEMO here

An alternative method involves utilizing the reduce function.

var joined_words = str.split(' ').reduce(function (previous, current) {
  var n = +current.match(/\d+/)[0];
  previous[n] = current;
  return previous;
}, []).slice(1).join(' ');

See the corresponding DEMO here

It's worth noting that you can extend this technique beyond just numbers 0-9. As long as you filter out any undefined elements, you'll achieve the desired result...

var str = 'is2 Thi1s T4est 3a Ye12s!';

var output = str.split(' ').reduce(function (previous, current) {
  var n = +current.match(/\d+/)[0];
  previous[n] = current;
  return previous;
}, []).slice(1).filter(function (element) {
  return element !== undefined;
}).join(' ');

View the updated DEMO here

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

Choose a variety of table rows based on the values of the data attributes that are

Is there a more efficient way to select all rows with data attributes id 1,2.. without specifying each row individually? I need some guidance on the best approach for this. Can anyone help me out? <table id="eTable"> <tr data-empid="A123" data- ...

One efficient way to handle multiple concurrent tasks in NodeJs is by using the forEach method to iterate

Having trouble getting the promises to return any values, as they are coming back empty. Despite following suggestions on Stack Overflow, I am still unable to resolve this issue. Frustration levels are high and I'm feeling lost; Can anyone help me pi ...

Tips for obtaining the sources of every image on a webpage and consolidating them in a single section

My goal is to preload all images on a webpage into a single division before the page loads. For example, if there are 5 images on the page (eg1.png, eg2.jpg, eg3.bmp, eg4.jpg, eg5.png), I want them to be contained within a div with the id 'pre'. ...

Having difficulty modifying the values of my input types on the edit page

After successfully adding user values from the add user page, I encounter an issue when attempting to edit these values such as firstname and lastname on the edit page. Please review the code snippet below for any possible errors. import React from ' ...

Inject some content into the page with the power of jQuery

Currently working with jQuery, I have a div containing H2 tags. <div id="preload"><h2></h2></div> I'm looking to understand how to use jQuery to insert text inside the <h2> tags The expected outcome should be: <div ...

Module not defined error

Here is the code for my HTML page: <!DOCTYPE html> <!-- define angular app --> <html ng-app="daily"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" c ...

Combining the redux toolkit function createAsyncThunk with Angular's HttpClient by leveraging the ApiService

Currently, I am working on incorporating @reduxjs/toolkit into an Angular project. Is there a way to pass an Angular service as a parameter to the callback of createAsyncThunk instead of utilizing fetch directly? I referenced the documentation for an exa ...

Is the concept of LinkedList index applicable in the field of Data Structures and Algorithms (DSA)?

Is there an index feature in LinkedList that allows for accessing elements like in arrays? If so, can you explain how the indexing works within the LinkedList concept? Thank you I am new to LinkedList and would like to grasp the fundamental concept behin ...

Activate Bootstrap modal using an anchor tag that links to a valid external URL as a fallback option

To ensure accessibility for users who may have javascript disabled, we follow a company standard of developing our web pages accordingly. Our target demographic still includes those familiar with VCRs blinking 12:00. One particular challenge involves a te ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

I seem to be having trouble locating the correct file location

Apologies for the simplicity of my question. I've been struggling to include the find.js file in my articles.js file. Despite trying multiple variations, I can't seem to get the pathname right and haven't found a solution online. Can someon ...

The entire DOM refreshes when a user updates the input field

In my React component, I am managing two states: inputText and students. The inputText state tracks the value of an input field, while the students state is an array used to populate a list of student names. The issue arises when the inputText state change ...

json request not functioning properly in Internet Explorer and experiencing difficulties with caching

Unfortunately, the code snippet provided below is compatible only with Firefox and not Internet Explorer. The JSON file breaks when it encounters the text "Meanscoil na mBraithre Criostaí": "2028425":[19, "Awaiting Correction", "", "Meanscoil na mBra ...

What is the best way to apply a class to a container when a component in AngularJS receives focus or is clicked?

I am trying to apply a class to the container when either the input field is focused or when the dropdown component receives focus or is clicked. The class should be removed when the focus is lost. The requirement is for the input container to have the &a ...

Sending a message to a specific client using socket.io

Currently delving into socket.io + node.js, I have mastered sending messages locally and broadcasting using the socket.broadcast.emit() function - where all connected clients receive the message. My next challenge is figuring out how to send a private mes ...

Tips for accessing the reference of a child when it is a functional component

Trying to implement a Higher Order Component (HOC) to access the ref of any component. It works perfectly fine when regular JSX is passed, but encounters issues when a functional component is passed: class GetRef extends React.Component { state = {}; ...

Use Typescript in combination with React/Redux to showcase a dynamic table on the

Looking to create a React TypeScript Redux application that showcases a table using an API endpoint provided at https://example.com/users The goal is to construct a table with 4 columns: Name, Email, City, and Company, utilizing the API response to popula ...

Scrolling automatically to the first empty mandatory field with the help of AngularJS

After utilizing angular js to create a form with 7 input elements, I encountered an issue. Upon clicking submit, the form should scroll up to the first blank required field. However, it is not accurately identifying the left blank field. Any suggestions on ...

Utilizing a JavaScript variable within a jQuery function as an attribute

var image = "path.png"; Is it possible to include the 'image' variable in the jQuery function like this? $('#mapfoto').prepend('<img id="theImg" src="http://path.gr/" + image />'); ...

Focusing on the final (but not ultimate) elements within a specified tag

I am facing a challenge with an HTML structure containing multiple instances of a certain element along with two p elements beneath each: <some_tag></some_tag> <p></p> <p></p> <some_tag></some_tag> <p> ...