Is it possible to maintain the original order of the array even after making modifications to

I am facing an issue where the database has incorrect naming conventions for rows. To avoid affecting website functionality, I cannot correct these conventions within the query itself. Thus, I have decided to use JavaScript to rename them correctly for display in the view.

In order to achieve this, I created a query that generates a fictional array like this:

Original Array

['Tree_Domestic', Rabbit, Unicorn, Cheetah_Domestic, Shark, Whale_Domestic]

The goal is to identify entries in the array that do not contain "_domestic" or "_international" and replace them with "_international". For instance, [Rabbit,Unaicorn,Shark] should be transformed into:

[Rabbit_International,Unicorn_International,Shark_International]

Although I successfully accomplished this task, I encountered one final hurdle,

The modified array rearranged alphabetically, which is undesirable. The desired array order should be:

['Tree_Domestic', Rabbit_International, Unicorn_International, Cheetah_Domestic, Shark_International, Whale_Domestic]

This specific order is essential because it aligns with the counting procedure applied on popular rows. If I modify the array before conducting the count, the results will not correspond to the original order of items in the array.

Below is my query:

$sql = 'SELECT animals,
COUNT(*)
FROM fictional_signup
WHERE usergroup NOT IN (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
 GROUP BY popular
 ORDER BY COUNT(*) DESC';

Javascript

var renameLocations = [];

dataLabel = <?php echo json_encode($locations) ?>;
dataCount = <?php echo json_encode($count) ?>;

for(t = 0; t < dataLabel.length; t++){
  if(dataLabel[t].includes('_Domestic') || dataLabel[t].includes('_International')){
    renameLocations.push(dataLabel[t]); 
  }
}
for(z = 0; z < dataLabel.length; z++){
  if(!dataLabel[z].includes('_Domestic') && !dataLabel[z].includes('_International')){
    renameLocations.push(dataLabel[z] + "_International"); 
  }
}

// Returns the correct naming conventions but the order is incorrect with the count.
console.log(renameLocations);

Answer №1

If you want to transform an array by modifying each entry, you can utilize the Array.prototype.map() function.

/*
$locations = [
    'Tree_Domestic',
    'Rabbit',
    'Unicorn',
    'Cheetah_Domestic',
    'Shark',
    'Whale_Domestic'
]
*/
dataLabel = <?php echo json_encode($locations) ?>.map(
    // The "e" variable represents individual entries in the array 
    function(e){
        // If an entry ends with _Domestic or _International,
        // keep it as is
        if (e.endsWith('_Domestic') || e.endsWith('_International'))
            return e;
        // Otherwise, append "_International" and use that instead
        else
            return e + "_International";
    }
)

The result will be:

[
    "Tree_Domestic",
    "Rabbit_International",
    "Unicorn_International",
    "Cheetah_Domestic",
    "Shark_International",
    "Whale_Domestic"
]

Answer №2

If you're looking to maintain the original order of elements in an array, one approach is to map the original array into a new array.

var startingArray = ['Tree_Domestic', 'Rabbit', 'Unicorn', 'Cheetah_Domestic', 'Shark', 'Whale_Domestic'];
var newArray;

newArray = startingArray.map(function(item, idx){
  if (item.indexOf('_Domestic') < 0 && item.indexOf('_International') < 0) {
    return item +'_International';
  }
  
  return item;
});

console.log(newArray);

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

Does each imported module in a Next.js app run multiple times?

There is a common understanding that when a module is imported multiple times within a JavaScript program, it only executes once during the first import. Informative article: The concept is straightforward: each module is evaluated just once, meaning th ...

Error occurred in AngularJS service due to incorrect data type

Looking to store the URL of a query in an AngularJS service like this: var mortgageloanService = angular.module('loanstreetIpadAppApp', []); mortgageloanService.factory('updateTable', function($http) { return { getParams: fun ...

Leverage the power of JavaScript to bring in a JSON file

Currently, I am working on building a website and utilizing a json file to store the necessary data for one of the pages. However, I am encountering difficulties when attempting to successfully import the data. My coding platform is repl.it. My attempts s ...

In JavaScript countdown timer, incorporate a leading zero to the minutes and seconds

I'm struggling to incorporate leading zeros into the minutes and seconds of this javascript countdown timer. I can't seem to make the leadingzero function work properly. The additional leadingzero function that I added doesn't appear to be f ...

Getting the value of a variable inside an onclick function

I am facing an issue with displaying the values of 2 variables inside an onclick event. I have tried the code below but it is not working. Can someone please help me solve this problem within the next 3 hours? var myCode = "12345"; var myCount = "5" $(&a ...

Is it considered acceptable to update the Vuex state solely by utilizing the payload parameter within a mutation?

Is it possible to iterate over Vuex data in a Vue file, identify the data that needs updating, and then pass that data to an action for committing, with the mutation handling the update? I'm uncertain because standard Vuex mutations require a 's ...

Having trouble with a JQuery selector not functioning properly when trying to select a class in the HTML that contains a

Looking for help with a JQuery selector to target the title of a YouTube video. Here's the HTML snippet: <div class="ytp-title-text"> <a class="ytp-title-link yt-uix-sessionlink" tabindex="13" target="_blank" ...

To handle async actions in Typescript with React and Redux, ensure that all actions passed to axios are plain objects. If you need to perform

Looking for assistance with Typescript, React, and Redux. export function fetchAllMeals (subject: string){ axios .get(`https://www.themealdb.com/api/json/v1/1/search.php?s=${subject}`) .then((response: any) => { console.log(response.data) ...

Ensuring your app is compatible with older versions of Node.js: A guide

Is there a way to develop a Node.JS application using the latest features of JS and Node.JS (like Node.JS v8 or even v13) and deploy it on an embedded Linux server with Node.JS v4 (Omega2, OpenWRT, MIPS arch)? I am looking for solutions or suggestions on ...

Optimal strategies for handling JavaScript in a one-page application

Currently, I am working on a single page app that changes the hash in the URL to load and modify the content of the page. I am contemplating the best approach for managing the JavaScript required by each "page". I have already developed a History module t ...

What is the best approach for managing Create/Edit pages in Next.js - should I fetch the product data in ServerSideProps or directly in the component?

Currently, I am working on a form that allows users to create a product. This form is equipped with react-hook-form to efficiently manage all the inputs. I am considering reusing this form for the Edit page since it shares the same fields, but the data wil ...

Refresh numerous pages

Currently, I'm working on a freelance project where I've been tasked with re-coding an outdated menu for my client. The website is built on static pages, so updating the menu manually on each page seems like a time-consuming and repetitive task. ...

The mysterious workings of the parseInt() function

As I begin my journey to self-teach JavaScript using HeadFirst JavaScript, I've encountered a minor obstacle. The chapter I'm currently studying delves into handling data input in forms. The issue arises when I attempt to utilize the updateOrder( ...

Reducing Repositioning in Marionette for Better Performance

I'm grappling with a web application that uses Marionette to render complex nested views. The challenge I face is minimizing reflows by ensuring child elements are rendered and placed in parent containers before being inserted into the DOM. How can I ...

What is the best way to eliminate duplicate values from an Array in ReactJS?

Hi there, I'm new to JavaScript and React. I need some help with a project I found on the React blog. I want to try solving it in my own way. This is the content of todoList.js: const todoList = [ {category: 'Sporting Goods', price: &a ...

Attempting to retrieve the parameters of a function from a nested function

Currently, I am utilizing three.js alongside a script similar to OrbitControls as my controller. Within my main.js file, I am passing a THREE.Group() to the controller as an argument with the intention of rotating the entire group. Issue 1: Once the gro ...

The dollar sign function operates properly, but encountering issues with the $.ajax function (non-slim)

I'm facing some issues with my jQuery code. I have included jQuery (not slim) and for some reason, $.ajax is failing. However, '$' and 'jQuery' functions are working fine. It seems like a simple problem but I can't seem to fi ...

I am in need of assistance in developing an image slider using react.js. Can you help

let projects = [{id: 1, img: "https://scontent-lax3-2.xx.fbcdn.net/v/t1.0-9/117405206_1535037326696077_4967665142447981078_o.png?_nc_cat=111&ccb=2&_nc_sid=730e14&_nc_ohc=XlNXGJF47E0AX8lB1fk&_nc_ht=scontent-lax3-2.xx&a ...

Utilizing Next.js for dynamic routing with [[...slug.js]] allows for comprehensive URL handling and seamless 404 page display for links leading back to the homepage - a feature

In order to achieve a single dynamic route for handling all requests in this application, I have created a file called [[...slug]].js. Data loading is managed using getServerSideProps(), allowing for server-side rendering. Notably, there are no index.js fi ...

What steps can I take to ensure the security of my Node.js endpoints and restrict access to them exclusively from my website?

I have implemented security measures for my Nodejs endpoints using the following code snippets... const corsOption = { origin: ['https://www.mywebsite.com'], }; app.use(cors(corsOption)); if (host !== "myendpoint.com") { return ...