我有一个问题,我有这个字符串数组:
[ "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" ]
我想创建一个按插入的输入值对该数组进行排序的方法,例如,如果我输入“ Platinum”,则该数组将首先显示铂金值。
谢谢!
答案 0 :(得分:2)
您可以对数组进行排序
let search = "Platinum";
arr.sort((x, y) => x == search ? -1 : y == search ? 1 : 0)
一个例子:
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 search = "Platinum";
arr.sort((x, y) => x == search ? -1 : y == search ? 1 : 0)
console.log(arr);