javascript 排序_JavaScript中的排序方法

javascript 排序

There are tons of sorting algorithms available like bubble sort, merge sort, insertion sort etc. You must have implemented some of these in other programming languages like C or C++. But in this article, I will be demonstrating the Sorting methods inbuilt in JavaScript.

有大量的排序算法可用,例如冒泡排序,合并排序,插入排序等。您必須已經用其他編程語言(例如C或C ++)實現了其中一些。 但是在本文中,我將演示JavaScript內置Sorting方法

This is way different from usual sorting algorithms you must have seen.

這與您必須看到的常規排序算法不同。

JavaScript code:

JavaScript代碼:

<html>
<head><title>COLA PRODUCTS.!!!</title></head>
<body>
<script>
document.write("<br>");
var products = [ 
{ name: "Grapefruit", calories: 170, color: "red", sold: 8200 },
{ name: "Orange", calories: 160, color: "orange", sold: 12101 },
{ name: "Cola", calories: 210, color: "caramel", sold: 25412 },
{ name: "Diet Cola", calories: 0, color: "caramel", sold: 43922 },
{ name: "Lemon", calories: 200, color: "clear", sold: 14983 },
{ name: "Raspberry", calories: 180, color: "pink", sold: 9427 },
{ name: "Root Beer", calories: 200, color: "caramel", sold: 9909 },
{ name: "Water", calories: 0, color: "clear", sold: 62123 }
];
function compareSold(colaA, colaB) {
if (colaA.sold > colaB.sold) {
return 1;
} else if (colaA.sold === colaB.sold) {
return 0;
} else {
return -1;
}
}
function compareName(colaA, colaB) {
if (colaA.name > colaB.name) {
return 1;
} else if (colaA.name === colaB.name) {
return 0;
} else {
return -1;
}
}
function compareCalories(colaA, colaB) {
if (colaA.calories > colaB.calories) {
return 1;
} else if (colaA.calories === colaB.calories) {
return 0;
} else {
return -1;
}
}
function compareColor(colaA, colaB) {
if (colaA.color > colaB.color) {
return 1;
} else if (colaA.color === colaB.color) {
return 0;
} else {
return -1;
}
}
function printProducts(products) {
for (var i = 0; i < products.length; i++) {
document.write(" Name: " + products[i].name + "                                          "+
"  Calories: " + products[i].calories +"                                          "+
" Color: " + products[i].color + "                                          "+
" Sold: " + products[i].sold);
document.write("<br>");
}
document.write("<br>");
}
products.sort(compareSold);
document.writeln("Products sorted by number of bottles sold:");
document.write("<br>");
printProducts(products);
products.sort(compareName);
document.write("Products sorted by name:");
document.write("<br>");
document.writeln();
printProducts(products);
products.sort(compareCalories);
document.write("Products sorted by calories:");
document.write("<br>");
printProducts(products);
products.sort(compareColor);
document.write("Products sorted by color:");
document.write("<br>");
printProducts(products);
</script>
</body>
</html>

Output

輸出量

Products sorted by number of bottles sold: 
Name: Grapefruit Calories: 170 Color: red Sold: 8200
Name: Raspberry Calories: 180 Color: pink Sold: 9427
Name: Root Beer Calories: 200 Color: caramel Sold: 9909
Name: Orange Calories: 160 Color: orange Sold: 12101
Name: Lemon Calories: 200 Color: clear Sold: 14983
Name: Cola Calories: 210 Color: caramel Sold: 25412
Name: Diet Cola Calories: 0 Color: caramel Sold: 43922
Name: Water Calories: 0 Color: clear Sold: 62123
Products sorted by name:
Name: Cola Calories: 210 Color: caramel Sold: 25412
Name: Diet Cola Calories: 0 Color: caramel Sold: 43922
Name: Grapefruit Calories: 170 Color: red Sold: 8200
Name: Lemon Calories: 200 Color: clear Sold: 14983
Name: Orange Calories: 160 Color: orange Sold: 12101
Name: Raspberry Calories: 180 Color: pink Sold: 9427
Name: Root Beer Calories: 200 Color: caramel Sold: 9909
Name: Water Calories: 0 Color: clear Sold: 62123
Products sorted by calories:
Name: Diet Cola Calories: 0 Color: caramel Sold: 43922
Name: Water Calories: 0 Color: clear Sold: 62123
Name: Orange Calories: 160 Color: orange Sold: 12101
Name: Grapefruit Calories: 170 Color: red Sold: 8200
Name: Raspberry Calories: 180 Color: pink Sold: 9427
Name: Lemon Calories: 200 Color: clear Sold: 14983
Name: Root Beer Calories: 200 Color: caramel Sold: 9909
Name: Cola Calories: 210 Color: caramel Sold: 25412
Products sorted by color:
Name: Diet Cola Calories: 0 Color: caramel Sold: 43922
Name: Root Beer Calories: 200 Color: caramel Sold: 9909
Name: Cola Calories: 210 Color: caramel Sold: 25412
Name: Water Calories: 0 Color: clear Sold: 62123
Name: Lemon Calories: 200 Color: clear Sold: 14983
Name: Orange Calories: 160 Color: orange Sold: 12101
Name: Raspberry Calories: 180 Color: pink Sold: 9427
Name: Grapefruit Calories: 170 Color: red Sold: 8200

Don't be scared...

別害怕...

The code is quite easy to understand.

該代碼很容易理解。

First, an array of objects has been created. Each object having the same set of properties.

首先,已創建對象數組。 每個對象具有相同的屬性集。

Arrays in JS have an inbuilt sort method. This sort method takes another comparing function defined by coders as an argument.

JS中的數組具有內置的排序方法。 這種排序方法采用編碼器定義的另一個比較函數作為參數。

The major principle behind all this is that sort method needs a function to compare two elements of the array on which sort method is called. When that function is to be called and on which two elements of an array it is to be called that is decided by the sort method.

所有這些背后的主要原理是sort方法需要一個函數來比較調用sort方法的數組的兩個元素。 當要調用該函數以及要在數組的哪兩個元素上調用時,該函數由sort方法決定。

Here I have defined four functions that are used to compare two objects of an array at a time. Each function compares two objects on the different basis. Like function, compareName compares two objects on the basis of name property of objects.

在這里,我定義了四個函數,用于一次比較一個數組的兩個對象。 每個函數在不同的基礎上比較兩個對象。 像函數一樣,compareName根據對象的name屬性比較兩個對象。

If the name of the first object is lexicographically larger than the name of the second object then 1 is returned to sort method if they are equal 0 is returned and if the name of the first object is lexicographically smaller than the name of the second object then -1 is returned to sort method.

如果第一個對象的名稱在字典上大于第二個對象的名稱,則將1返回到sort方法,如果它們相等,則返回0,并且如果第一個對象的名稱在字典上小于第二個對象的名稱,則-1返回排序方法。

Other three functions compareSold, compareCaloriescompareColor work In exactly same manner.

其他三個函數compareSold , compareCaloriescompareColor以完全相同的方式工作。

Printproducts is a simple function used to print the input array.

Printproducts是用于打印輸入數組的簡單函數。

Document.write is like console.log which is used to display text on corresponding HTML page.

Document.write類似于console.log ,用于在相應HTML頁面上顯示文本。

I hope I have made everything very clear and precise.

我希望我已經使所有內容都非常清楚和準確了。

Try to make your own compare functions and use the inbuilt sort method on different arrays.

嘗試制作自己的比較函數,并在不同的數組上使用內置的sort方法。

翻譯自: https://www.includehelp.com/code-snippets/sorting-methods-in-javascript.aspx

javascript 排序

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/378015.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/378015.shtml
英文地址,請注明出處:http://en.pswp.cn/news/378015.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

LeetCode 二叉樹、N叉樹的最大深度與最小深度(遞歸解)

目錄104. 二叉樹的最大深度559. N叉樹的最大深度111. 二叉樹的最小深度之前的筆記中&#xff0c;已經用層序遍歷解決過這個問題了現在試著用深度的解法去求解104. 二叉樹的最大深度 給定一個二叉樹&#xff0c;找出其最大深度。 二叉樹的深度為根節點到最遠葉子節點的最長路徑…

十、模板匹配

一、概念 模板匹配就是在整個圖像區域發現與給定子圖像匹配的小塊區域。 需要首先給定一個模板圖像A&#xff0c;和一個待檢測圖像B。 在待檢測圖像B上&#xff0c;從左往右&#xff0c;從上往下計算待檢測圖像B和模板圖像A所重疊的匹配度&#xff0c;匹配度越高則兩者相同的可…

基于WF的意見征集4(淺析)

接口項目&#xff1a;IClass&#xff08;項目名稱&#xff09; HTHuiFuusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Workflow.Runtime;using System.Workflow.Activities;namespace IClass{ /// <summary> /…

那些VisualStudio隱藏的調試功能

VisualStudio是一個強大的調試工具&#xff0c;里面很多隱藏功能少有人問津&#xff0c;但是在特定場景可以節省你很多時間&#xff0c;本文主要介紹一些VisualStudio調試相關的隱藏功能&#xff0c;歡迎大家補充。 運行到指針(Run to cursor) 大多數人用Visual Studio在調試程…

php連接數據庫代碼_PHP代碼連接各種數據庫

php連接數據庫代碼1)用PHP連接MySQL (1) Connecting with MySQL in PHP) <?php$host "localhost";$uname "username";$pw "password";$db "newDB";try {$conn new PDO("mysql:host$host;dbname$db", $uname, $pw);…

【C++ grammar】對象和類(創建對象、對象拷貝、分離聲明與實現)

目錄1、用類創建對象1、面向對象的特征2、對象由什么構成3、如何定義對象4、創建對象并訪問對象成員1. Constructors(構造函數)2. Constructing Objects (創建對象)3. Object Member Access Operator(對象訪問運算符)2、對象拷貝以及分離聲明與實現1、類是一種數據類型1.1. 定義…

十一、圖像二值化

一、二值圖像 其實就是把圖像轉換為只有黑白的兩種顏色圖像&#xff0c;即像素值非零即一 三角閾值二值化 對一個圖像進行操作&#xff0c;獲取圖像的直方圖&#xff0c;找到波峰和波谷進行連線設為線段A&#xff0c;每個點做有關線段A的垂線垂足在線段A上&#xff0c;最后將…

百度地圖LV1.5實踐項目開發工具類bmap.util.jsV1.2

/*** 百度地圖使用工具類-v1.5* * author boonya* date 2013-7-7* address Chengdu,Sichuan,China* email boonyasina.com* company KWT.Shenzhen.Inc.com* notice 有些功能需要加入外部JS庫才能使用&#xff0c;另外還需要申請地圖JS key .* 申請地址&#xff1a;http…

isatty_帶有示例的Python File isatty()方法

isatty文件isatty()方法 (File isatty() Method) isatty() method is an inbuilt method in Python, it is used to check whether a file stream is an interactive or not in Python i.e. a file stream is connected to a terminal device. If a file is connected to a ter…

地毯店 如何辨別地毯的好壞?

在實地選購地毯品牌時&#xff0c;許多地方需要引起注意&#xff0c;而且要顯得專業&#xff0c;這樣才能科學深入地辨別地毯的好壞。比如&#xff0c;辨明拉絞地毯和抽絞地毯兩種工藝的打結方法幾乎相同&#xff0c;只是變絞形式上有所區別。抽絞的方式較古老&#xff0c;一般…

十二、圖像金字塔

一、原理 reduce高斯模糊降采樣 expand擴大卷積 PyrDown&#xff1a;降采樣 PyrUp&#xff1a;還原 二、高斯金字塔 import cv2 import numpy as np from matplotlib import pyplot as pltdef pyramid(image):level 3temp image.copy()pyramid_image []for i in range(le…

java uuid靜態方法_Java UUID toString()方法與示例

java uuid靜態方法UUID類toString()方法 (UUID Class toString() method) toString() method is available in java.util package. toString()方法在java.util包中可用。 toString() method is used for string denotation of this UUID. toString()方法用于此UUID的字符串表示…

LeetCode 110. 平衡二叉樹思考分析

題目 給定一個二叉樹&#xff0c;判斷它是否是高度平衡的二叉樹。 本題中&#xff0c;一棵高度平衡二叉樹定義為&#xff1a; 一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過1。 示例 1: 給定二叉樹 [3,9,20,null,null,15,7] 3 / 9 20 / 15 7 返回 true 。 示例 2…

Redhat配置XDMCP及相關linux命令

為了能夠使用 Xwin32 或 Xmanager 登錄到 Linux 主機所進行的配置。需要首先在linux上進行相關配置 1.“系統”菜單中選擇“管理”下的“登錄屏幕” 2.出現“登錄窗口首選項”窗口。選擇“遠程”選項卡&#xff0c;將“樣式”改為:“與本地相同” 3.選擇“安全”選項卡&#xf…

充實的日子里忙忙碌碌

實習已經有一個多月了&#xff0c;話說這個月發工資就有我的份兒了&#xff0c;哇咔咔~~~感覺忙忙碌碌的生活其實很充實的。工作日每天都是7點10分左右起來&#xff0c;8點半到公司買早飯吃東西&#xff0c;9點上班開工。先羅列要干的東西&#xff0c;然后一項一項完成&#xf…

十三、圖像梯度

一、兩種算子 一階導數—Sobel算子 水平梯度&#xff1a; 垂直梯度&#xff1a; 最終圖像梯度&#xff1a; 二階導數—Laplacian算子 在二階導數的時候&#xff0c;最大變化處的值為零&#xff0c;即邊緣是零值。 常見的拉普拉斯算子&#xff1a;、其所有元素之和為零。…

Java Formatter out()方法與示例

格式化程序類out()方法 (Formatter Class out() method) out() method is available in java.util package. out()方法在java.util包中可用。 out() method is used to get Appendable for the output. out()方法用于獲取輸出的Appendable。 out() method is a non-static meth…

SQL2008,SQL2005存儲過程解密

SQL2008,SQL2005存儲過程解密 下載&#xff1a;附件 SQL2008,SQL2005存儲過程解密第一步操作步驟&#xff1a;程序->Sql Server2005-> 配置工具-> Sql Server 外圍應用配置器-> 功能的外圍應用配置器-> DataBase Engine-> DAC -> 啟用遠程DAC 第二步&a…

LeetCode 257. 二叉樹的所有路徑 思考分析

目錄題目思路一&#xff1a;深度遞歸思路二&#xff1a;廣度迭代關于回溯題目 給定一個二叉樹&#xff0c;返回所有從根節點到葉子節點的路徑。 說明: 葉子節點是指沒有子節點的節點。 示例: 輸入: 輸出: [“1->2->5”, “1->3”] 解釋: 所有根節點到葉子節點的路…

自定義django的Template context processors

簡要步驟&#xff1a; 1.編輯一個函數: def media_url(request):from django.conf import settingsreturn {media_url: settings.MEDIA_URL}2.配置settings&#xff1a; TEMPLATE_CONTEXT_PROCESSORS (myapp.context_processors.media_url,) 3.確保幾點&#xff1a; 1&#xf…