Sorting an array of strings based on user input using Vue.js

I'm facing an issue where I have an array of various strings:

[ "Aluminum", "Basic Materials", "Broad Credit", "Broad Market", "Cocoa", "Coffee", "Consumer Cyclicals", "Consumer Non-cyclicals", "Copper", "Corn", "Cotton", "Crude Oil", "Energy", "Extended Market", "Financials", "Freight", "Gasoline", "Global Macro", "Gold", "Grains", "Health Care", "High Dividend Yield", "High Yield", "Industrials", "Investment Grade", "Large Cap", "Lead", "Livestock", "Long AUD, Short USD", "Long CAD, Short USD", "Long CHF, Short USD", "Long CNY, Short USD", "Long EUR, Short USD", "Long Emerging Markets Basket, Short USD", "Long GBP, Short USD", "Long Global Basket, Short USD", "Long INR, Short USD", "Long JPY, Short USD", "Long SEK, Short USD", "Long SGD, Short USD", "Long USD, Short AUD", "Long USD, Short CHF", "Long USD, Short EUR", "Long USD, Short GBP", "Long USD, Short Global Basket", "Long USD, Short JPY", "Long/Short", "Metals", "Micro Cap", "Mid Cap", "Natural Gas", "Nickel", "Palladium", "Platinum", "Real Estate", "Silver", "Small Cap", "Softs", "Soybeans", "Spreads", "Sugar", "Target Outcome", "Target Risk", "Technology", "Telecommunications", "Theme", "Tin", "Total Market", "Utilities", "Volatility", "Wheat" ]

I am looking to devise a method that will sort this array based on a given input value. For instance, if the input is "Platinum," then the array should display the platinum value first.

Thank you!

Answer №1

If you want to organize your array, you can use the following method:

let target = "Platinum";
arr.sort((x, y) => x == target ? -1 : y == target ? 1 : 0)

Here's an illustration:

let arr = ["Aluminum", "Basic Materials", "Broad Credit", "Broad Market", "Cocoa", "Coffee", "Consumer Cyclicals", "Consumer Non-cyclicals", "Copper", "Corn", "Cotton", "Crude Oil", "Energy", "Extended Market", "Financials", "Freight", "Gasoline", "Global Macro", "Gold", "Grains", "Health Care", "High Dividend Yield", "High Yield", "Industrials", "Investment Grade", "Large Cap", "Lead", "Livestock", "Long AUD, Short USD", "Long CAD, Short USD", "Long CHF, Short USD", "Long CNY, Short USD", "Long EUR, Short USD", "Long Emerging Markets Basket, Short USD", "Long GBP, Short USD", "Long Global Basket, Short USD", "Long INR, Short USD", "Long JPY, Short USD", "Long SEK, Short USD", "Long SGD, Short USD", "Long USD, Short AUD", "Long USD, Short CHF", "Long USD, Short EUR", "Long USD, Short GBP", "Long USD, Short Global Basket", "Long USD, Short JPY", "Long/Short", "Metals", "Micro Cap", "Mid Cap", "Natural Gas", "Nickel", "Palladium", "Platinum", "Real Estate", "Silver", "Small Cap", "Softs", "Soybeans", "Spreads", "Sugar", "Target Outcome", "Target Risk", "Technology", "Telecommunications", "Theme", "Tin", "Total Market", "Utilities", "Volatility", "Wheat"]

let target = "Platinum";
arr.sort((x, y) => x == target ? -1 : y == target ? 1 : 0)
console.log(arr);

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

Enhance design based on scrolling function in React

I've been trying to update the color of my header when a user scrolls the page, but for some reason, my onScroll method isn't working. Can anyone help me figure out why and how to solve this issue? The onScroll method is triggered by the bottom T ...

Access the plugin object from a Vue.js 2 component using typescript

I devised a plugin object to handle the regular expressions used in my application in a more global manner. Here's an example of how it looks: import Vue from "vue"; Vue.prototype.$regex = { //isEmail function implementation goes here } ...

In the year 2021, eliminate linked documents using mongoose/MongoDB middleware

After extensive research on stack overflow, I attempted various solutions for deleting referenced documents in MongoDB using node.js. Unfortunately, most of them either utilize deprecated methods or simply do not function as expected. Within my applicatio ...

Error in the execution of the if statement within $(window).width() when it is not supposed to be

Hello everyone, I'm facing an issue with the jQuery $(window).width when using if statements. It seems that my function is still running even when the window width is smaller than 991 pixels, although my if statement specifies that it should run only ...

Deploying scripts after CloudFormation deployment

After each deployment on AWS, I have a specific npm script called db:migrate that I need to run. This script is responsible for executing the migrate.js file, which handles all database migrations. Currently, my deployments are managed using AWS CloudForm ...

Verify if the form has been refreshed in React JS

In my React application, I have a form inside a modal pop-up. When the user closes the pop-up, I want to check for any changes made in the form fields. If there are changes, I will display a confirmation modal; if not, I will simply close the pop-up. <F ...

"Encountered a type error: The .join method is not recognized as a function

Hello everyone, I've encountered an issue that has me a bit stumped. I recently took over a project and found a problem in which the previous developer was attempting to join an array of strings. Unfortunately, when I try to build the project, I keep ...

Using AngularJS and $http PUT method to send files in the request body

I am currently facing an issue with uploading files via an API call using the PUT method. After successfully uploading a file, I am encountering problems where the resulting file size is larger than expected and cannot be opened. For example, a 234 kb jpg ...

The processing time for this request is unreasonably long

My website is built using Laravel and Vue.js. I am facing an issue where a function takes more than 2 minutes to execute, resulting in the following error: 500 Internal Server Error Request Timeout This request takes too long to process and is timed out b ...

Stop files from being downloaded every time the page is visited

Within my Vue.js application, there is an animation that appears on a specific page. However, each time I visit that page, the assets for the animation are re-downloaded from scratch. Although the app does get destroyed when leaving the page, using v-show ...

Buttons for toggling D3 bubble chart display mode

As a beginner in D3.js, I am exploring the creation of a bubble chart with a toggle button to switch between different presidential campaign candidates. While I succeeded in making the chart for one candidate, I am encountering difficulties implementing th ...

Struggling to process the JSON response generated by PHP

Currently, I am utilizing the pmxdr library to execute a cross-domain call from jQuery to PHP and receive a JSON response. Despite this, I am struggling to properly handle the response. When I attempt to display it in HTML, it appears as: {"title":"Mr","f ...

For every multi-dimensional array within PHPExcel

Can anyone help me with looping through a multidimensional array in PHP Excel? Here is the code I am currently using: $objWorkSheet = $this->excel->createSheet(1); //Setting index when creating $colors = array( array("A1", "B1", "C1", " ...

Identifying and capturing changes in child scope events or properties in Angular

I am encountering an issue with my form directive where I need to intercept ng-click events nested within varying child scopes of the form element. However, I am struggling to hook into these events or child scope properties in a generic way. For demonstr ...

Various successful functions in Ajax

I am currently using an Ajax script to fetch data from my database and insert it into multiple textboxes. Along with posting the data, I also need to perform calculations using these textboxes. However, upon running the script, I noticed that all calculat ...

Verify the presence of the input post in the mongo database

Currently, I am utilizing the following node js code to store data in a database... //connect to database db.on('error', console.error); db.once('open', function() { router.post('/register', function(request, response) { ...

Refresh the HTML webpage using AJAX technology

I am trying to implement a simple html page with a single table that updates in the background every 5 seconds. The traditional solution of using <meta http-equiv="refresh" content="5"> is not suitable as it would disrupt the user experience by displ ...

Struggling to comprehend c++ string literals

I've encountered an issue with my C++ program - it does not execute and shows an error message saying that C++ forbids converting string constants to char*. How can I go about fixing this error? #include <cstring> #include <iostream> using ...

Refresh the view in AngularJS following a successful $http.get request

I have a <ul> in my HTML view that is populated based on a $http.get request. HTML: <div id="recentlyReleased" ng-controller="sampleRecordController as recCtrl"> <h1>Sample Records</h1> <ul> <li class= ...

Ways to streamline your Jquery/Ajax code: Eliminate repetitive sections

Seeking guidance on optimizing my Jquery/Ajax code that involves sending GET requests. I've noticed there's quite a bit of repetition. How can I streamline this code effectively? $(".add_to_cart").click(function() { product_slug = $(this).at ...