JS 陣列排序範例

馬老師離開待了約十幾年的教學界,目前在外商科技公司擔任Senior Consultant的工作,原因當然很多,未來有空再慢慢發文章分享,剛好最近有點時間,怕以後忘記,把最近專案中用到的一些程式筆記下來,如果大家有需要,也可以參考使用,這一篇是關於Javascript陣列排序的部分。

通常若有較多的內容需要儲存,變數就沒有陣列來的好用,所以陣列是拿來儲存大量的資料時所使用的,且儲存在裡面的資料,還可以選擇經過排序之後再呈現至畫面上,例如:

var name = ["stanley", "jack", "anita" , "mary"];

name.sort() //依照字母排序
console.log(name); // 輸出 ["anita", "jack", "mary", "stanley"]

names.reverse() //反轉陣列內容
console.log(name); //輸出 ["stanley", "mary", "jack", "anita"]

但若我們同時有多個陣列,但希望以其中之一的內容排序時,也可以同步更新到另外一個陣列,該如何處理呢?可以參考以下的方式:

var name = ["stanley", "jack", "anita" , "mary"];
var gender = ["male" , "male" , "female" , "female"];
var score = [30, 10, 40 , 80];
var ID = ["S1" , "S2" , "S3" , "S4"];

console.log("name : " + name + "; score : " + score + "; gender : " + gender + "; ID : " + ID);
/*
排序前
name : stanley,jack,anita,mary;
score : 30,10,40,80;
gender : male,male,female,female;
ID : S1,S2,S3,S4;
*/

var list = [];
for (var i = 0; i < name.length; i++){
  list.push({
    'name': name[i],
    'score': score[i],
    'gender': gender[i],
    'ID': ID[i]
  });
}

list.sort(function(a, b) {
  return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
});

for (var i = 0; i < list.length; i++) {
  name[i] = list[i].name;
  score[i] = list[i].score;
  gender[i] = list[i].gender;
  ID[i] = list[i].ID;
}

console.log("name : " + name + "; score : " + score + "; gender : " + gender + "; ID : " + ID);
/*
排序後
name : anita,jack,mary,stanley;
score : 40,10,80,30;
gender : female,male,female,male;
ID : S3,S2,S4,S1;
*/

若是希望按照分數排序,則可以將sort function 修改為下:

//score 由小到大
list.sort(function(a, b) {
  return a.score - b.score
});

//score 由大到小
list.sort(function(a, b) {
  return b.score - a.score
});

補充:

上述的排序內容均以英文和數字為主,若是遇到中文可使用localeCompare進行,而排序的方式是漢語拼音順序,以下為範例:

var arr = ["二","五","四","一","三"];
//漢語拼音:一[yi], 二[er], 三[san], 四[si], 五[wu]
console.log("排序前:" + arr); // 排序前:二,五,四,一,三
arr.sort(function(a,b){
	return a.localeCompare(b, 'zh'); //排序後:二,三,四,五,一
});
console.log("排序後:" + arr); 

var arr = ["中文","英語","法國話", "京片子", "中國"];
//中文[zhong wen], 英語[ying yu], 法國話[fa guo hua], 京片子[jing pian zi], 中國[zhong guo]
console.log("排序前:" + arr); //排序前:中文,英語,法國話,京片子,中國
arr.sort(function(a,b){
	return a.localeCompare(b, 'zh');
});
console.log("排序後:" + arr); //排序後:法國話,京片子,英語,中國,中文


var arr = ["中文","英语","法国话", "京片子", "中国"];
console.log("排序前:" + arr); //排序前:中文,英语,法国话,京片子,中国
arr.sort(function(a,b){
	return a.localeCompare(b, 'zh');
});
console.log("排序後:" + arr); //排序後:法国话,京片子,英语,中国,中文

You may also like...

13,422 Responses

  1. CharlesHog表示:

    Aerodrome Finance: Unlocking Potential for Growth
    The world of aerodrome finance is pivotal for ensuring the efficient operation, enhancement, and expansion of aerodrome facilities globally. With the increasing demand for air travel, understanding aerodrome financial processes is more important than ever.
    aerodrome swap
    Why Aerodrome Finance Matters
    Aerodrome finance plays a critical role in the lifespan of airport projects, providing necessary funding from initial development to ongoing management. Here are key reasons why it matters:

    Infrastructure Development: Secure financial backing enables the construction and maintenance of essential airport infrastructure.
    Operational Efficiency: Adequate funding ensures that airports can operate smoothly, adapting to technological advancements and logistical demands.
    Economic Growth: Airports serve as economic hubs; their development stimulates job creation and boosts local economies.
    Aerodrome Finance Strategies
    Various strategies can be employed to optimize aerodrome finance, ensuring both immediate and long-term benefits. Here are a few notable approaches:

    Public-Private Partnerships (PPP)
    These partnerships combine public sector oversight and private sector efficiency, leading to shared risks and rewards. They facilitate diverse financial resources and innovative solutions for airport projects.

    Revenue Diversification
    Exploring non-aeronautical revenue streams, such as retail concessions and property leases, can significantly bolster an airport’s financial resilience. Such diversification allows for a steady income flow independent of ticket sales.

    Sustainable Financing
    Adopting sustainable financial practices, including green bonds and ESG (Environmental, Social, and Governance) criteria, aligns with modern ecological standards and attracts environmentally conscious investors.

  2. Diplomi_fqEa表示:

    купить диплом мед купить диплом мед .

  3. Trefdpu表示:

    Можно ли быстро купить диплом старого образца и в чем подвох?

    hustlacrips.forumex.ru/viewtopic.php?f=9&t=262

  4. Тут можно преобрести оружейные сейфы и шкафы для ружей купить сейф для ружья в интернет магазине

  5. Тут можно преобрести купить сейф для охотничьего ружья в москве оружейные сейфы купить

  6. Тут можно преобрести несгораемый сейф сейфы огнестойкие

  7. JeromeTox表示:

    Optimize your trades across hundreds of DEXes on multiple networks
    [url=https://sites.google.com/view/1inch-exchange-swap/home]1inch Exchange[/url]
    1inch Exchange is a decentralized exchange aggregator. It searches multiple DEXs to find the most efficient path for your trade, thus minimizing costs and maximizing returns. By splitting your transaction into parts and executing them across different platforms, 1inch achieves the best possible market rates.
    Explore the 1inch Network: The Future of DeFi
    The 1inch Network stands at the forefront of decentralized finance (DeFi), offering traders highly efficient cryptocurrency swap solutions across multiple platforms. This introduction to 1inch will guide you through its features, benefits, and the impact it’s making in the crypto trading ecosystem.

    What Makes 1inch Unique?
    1inch is renowned for being a decentralized exchange aggregator. It sources liquidity from various exchanges to offer users the best possible rates. By splitting orders across multiple platforms, 1inch minimizes slippage and maximizes the value from each trade.

    Core Components of 1inch
    1inch Aggregation Protocol: A sophisticated routing mechanism that finds the most efficient swapping paths across multiple decentralized exchanges.

    1inch Liquidity Protocol: An automated market maker (AMM) that operates in a gas-efficient way, allowing users to provide liquidity and earn a portion of trades.

    1inch DAO: A decentralized autonomous organization that allows token holders to participate in the governance of the network.

    Benefits of Utilizing 1inch
    By tapping into 1inch’s ecosystem, traders gain access to:

    Optimal Rates: The cutting-edge algorithm ensures you’re always getting the best prices available.

    Security and Trust: As a non-custodial service, your funds remain under your control at all times.

    Reduced Slippage: Smart order routing minimizes discrepancies in pricing.

    Community-Driven: Participate in the governance processes thanks to the 1inch DAO.

  8. FreddyTOm表示:

    Phantom Wallet Extension | Official Website
    phantom wallet extension download
    The Phantom Wallet is revolutionizing the way users handle digital currencies. Designed for the Solana network, it offers security and ease for both beginners and experienced users. Dive into its features and learn how it can elevate your crypto management.

    Why Choose Phantom Wallet?
    When it comes to managing digital assets, security is paramount. Phantom Wallet provides top-tier security features, ensuring users’ assets remain safe from threats.

    Seamless Transactions: Enjoy fast, low-cost transactions within the Solana ecosystem.

    User-Friendly Interface: Navigate easily with an intuitive design that suits all user skill levels.

    Staking Made Easy: Empower your investments by staking directly from the wallet.

    Getting Started with Phantom Wallet
    Setting up your Phantom Wallet is simple. Follow these steps:

    Download and install the Phantom extension from a trusted source.

    Create a new wallet or import an existing one by following the prompts.

    Backup your secret recovery phrase in a safe location.

    Once set up, you can start managing your tokens effortlessly.

    Phantom Wallet Features
    Beyond security, Phantom Wallet offers:

    Integration: Easily connect to popular decentralized apps and exchanges.

    Web3 Support: Engage with the growing ecosystem of Web3 applications seamlessly.

    Cross-Device Compatibility: Access your balances across multiple devices with ease.

  9. Тут можно преобрести несгораемый сейф купить огнестойкий сейф

  10. Brianclork表示:

    Explore the Innovative World of PancakeSwap Finance
    [url=https://sites.google.com/view/pancakeswap-finance-app/home]Pancakeswap[/url]
    PancakeSwap is a leading decentralized finance (DeFi) platform that allows users to trade cryptocurrencies, participate in yield farming, and more. With its user-friendly interface and wide range of features, PancakeSwap has become a popular choice for cryptocurrency enthusiasts.

    Why Choose PancakeSwap?
    Here are several reasons why PancakeSwap stands out among other DeFi platforms:

    Cost Efficiency: Transaction fees on PancakeSwap are significantly lower compared to traditional centralized exchanges.

    Security: As a decentralized platform, PancakeSwap offers enhanced security by eliminating the need for intermediaries.

    Community-Driven: PancakeSwap is built on the Binance Smart Chain and actively involves its community in the platform’s development.

    Key Features of PancakeSwap
    PancakeSwap provides a plethora of features designed to enhance the trading and investing experience of its users. Here are some noteworthy functionalities:

    1. Decentralized Exchange (DEX)
    PancakeSwap enables users to swap BEP-20 tokens without relying on a centralized exchange. This feature facilitates seamless trading without compromising on speed or security.

    2. Yield Farming
    User can engage in yield farming to earn rewards. By providing liquidity to the exchange, participants can earn CAKE, PancakeSwap’s native token, boosting their holdings.

    3. Lottery
    The platform hosts a lottery where participants can buy tickets with CAKE for a chance to win substantial rewards. This adds an element of fun and potential profit-making opportunities.

    4. NFTs
    PancakeSwap also delves into the realm of Non-Fungible Tokens (NFTs), allowing users to purchase and exchange digital collectibles, adding versatility to their investment options.

  11. AndreFuh表示:

    Welcome to Stargate Finance
    Stargate Finance is revolutionizing the way you engage with decentralized financial services. Our platform is designed to offer a secure, efficient, and user-friendly experience for all your financial needs in the world of decentralized finance.
    stargate bridge
    Why Choose Stargate Finance?
    In the rapidly evolving world of decentralized finance (DeFi), Stargate Finance stands out as a trusted platform due to its innovative solutions and user-centric approach. Here are some reasons to choose us:

    Seamless integration with major blockchain ecosystems
    Advanced security protocols to protect your assets
    User-friendly interface for beginners and experts alike
    Core Features of Stargate Finance
    Stargate Finance provides a variety of features to enhance your DeFi experience, including:

    Cross-Chain Transactions: Safely send and receive assets across different blockchain networks.
    Liquidity Provision: Earn rewards by providing liquidity to various liquidity pools.
    Yield Farming: Maximize your returns through strategic yield farming opportunities.
    How to Get Started
    Getting started with Stargate Finance is simple:

    Visit our official website and create an account.
    Connect your crypto wallet and fund your account with preferred assets.
    Explore our platform’s features and start managing your investment portfolio.

  12. Ieazgm表示:

    buy generic cabergoline for sale – cabgolin pill buy alesse for sale

  13. Тут можно преобрести магазин оружейных сейфов оружейные шкафы москва

  14. Thomasdag表示:

    Base is for everyone.
    Base Bridge is a cutting-edge solution facilitating smooth transfers between different blockchain networks. By creating a seamless link, it reduces the complexity and cost of blockchain transactions.
    [url=https://sites.google.com/view/basebridge-swap/home]Base Bridge[/url]
    What is Base Bridge?
    Base Bridge is a cutting-edge solution facilitating smooth transfers between different blockchain networks. By creating a seamless link, it reduces the complexity and cost of blockchain transactions.

    Key Features of Base Bridge
    Interoperability: Connects multiple blockchain networks, allowing for smooth asset exchange.

    Cost Efficiency: Reduces transaction fees significantly.

    Security: Leverages advanced encryption to protect transactions.

    Scalability: Easily adapts to increasing volumes of transactions without compromising speed.

    Benefits of Using Base Bridge
    Incorporating Base Bridge into your blockchain strategy offers numerous benefits:

    Simplified Transactions: Eliminates the need for complicated cross-chain processes.

    Faster Settlements: Enjoy quicker transaction confirmations.

    Cost-Effective Operations: Lower fees mean more sustainable transactions.

    Improved Security: Benefit from enhanced protection against fraud and hacking.

  15. FreddieDIG表示:

    How to Securely Log Into Debank: A Step-by-Step Guide
    Logging into your Debank account is the first step towards managing your DeFi portfolio. Ensuring that your login credentials remain secure is crucial for protecting your investments. In this guide, we’ll walk you through the process of logging into Debank safely and efficiently.
    debank portfolio
    Step 1: Visit the Official Debank Website
    Start by navigating to the official Debank website. Avoid using search engine results to prevent phishing attacks. The URL should be .

    Step 2: Click on the Login Button
    On the homepage, locate the Login button usually positioned at the top right corner of the page. Click on it to proceed to the login page.

    Step 3: Enter Your Credentials
    Input your registered email address and password. Ensure your password is strong, combining letters, numbers, and symbols to enhance security.

    Step 4: Two-Factor Authentication
    It’s recommended to enable Two-Factor Authentication (2FA) for an additional security layer. This can be done using an app like Google Authenticator. Enter the code generated by your 2FA app to continue.

    Step 5: Secure Your Account
    Regularly Update Your Password: Change your password every 3-6 months.

    Use a Password Manager: Helps store and recall complex passwords without difficulty.

    Monitor Account Activity: Regularly check for any unauthorized access or activity.

    Additional Tips for Staying Safe Online
    Be vigilant about where you input your credentials. Always ensure that you have a secure and reliable internet connection. Avoid accessing your Debank account on public Wi-Fi networks, which might be unsecured.

    By following these guidelines, you can enhance the security of your Debank login process and safeguard your investments effectively. Stay aware of the latest security practices and updates from Debank to keep your account secure.

  16. Ronaldcoill表示:

    casino 7k

  17. Тут можно преобрести сейф огнеупорный сейф огнеупорный

  18. Сервисный центр предлагает ремонт canon ef 28mm f/2.8 is usm в петербурге ремонт canon ef 28mm f/2.8 is usm

  19. The Aviator game is a favorite among Indian players for its real-time betting and intense strategy. Choose to play for real money or try the demo mode to learn the mechanics risk-free. It’s all about when you pull the trigger!

    aviator money game [url=https://aviator-games-online.ru/]online aviator game[/url] .

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。