简体   繁体   English

使用比较函数对数组进行排序 - javascript

[英]Sorting an array with a compare function - javascript

I came across this sorting of an array and I do not understand the compare function at the point where '-1 : 1' is included.我遇到了这种数组排序,但我不理解包含“-1:1”的比较函数。 Please can some one explain to me what the compare function is doing exactly?请有人向我解释一下比较功能到底在做什么?

 const rows = [ createECG('ad0917d4-e02d-4c46-a5aa-dd83717684e9', '28/06/2022', 'pending'), createECG('9034124a-2ac8-4d52-8711-ef1351a5c18a', '18/05/2022', 'complete'), createECG('a2a7a1f4-81a0-4b70-b1e2-ee7a384a1f4f', '01/05/2022', 'pending'), createECG('e5427e62-5897-4eee-a6a6-8f9925feef96', '21/04/2022', 'complete') ].sort((a) => (a.status === 'pending' ? -1 : 1)); // The object 'a' has a property called 'status' console.log(rows); function createECG(id, date, status) { return {id, date, status}; }

The comparison function returns -1 if the first argument a as lower than b if its status is pending .如果第一个参数a低于b如果其状态为pending ,则比较函数返回-1 This indicates that a is lower than b , so it should be sorted ahead.这表明a低于b ,因此应该提前排序。 The intended result is that all the pending elements will be at the front of the result.预期的结果是所有pending的元素都将位于结果的前面。

But this isn't really valid, because the comparison function is required to be consistent -- if a is lower than b , then b should not also be lower than a .但这并不是真正有效的,因为比较函数需要保持一致——如果a低于b ,那么b也不应该低于a When it's comparing two pending objects, it will return -1 when they're passed in either order.当它比较两个挂起的对象时,当它们以任一顺序传递时,它将返回-1 The comparison function should return 0 in this case, but it doesn't.在这种情况下,比较函数应该返回0 ,但事实并非如此。

You need to take the delta of the comparison for a symmetrically sorting.您需要采用比较的增量进行对称排序。

 function createECG(id, date, status) { return { id, date, status }; } const rows = [ createECG('ad0917d4-e02d-4c46-a5aa-dd83717684e9', '28/06/2022', 'pending'), createECG('9034124a-2ac8-4d52-8711-ef1351a5c18a', '18/05/2022', 'complete'), createECG('a2a7a1f4-81a0-4b70-b1e2-ee7a384a1f4f', '01/05/2022', 'pending'), createECG('e5427e62-5897-4eee-a6a6-8f9925feef96', '21/04/2022', 'complete') ] .sort((a, b) => (b.status === 'pending') - (a.status === 'pending')); console.log(rows);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

排序就像过滤一样,你的代码意味着... 当 a.status === 'pending' 等于 1 时,表示该项目的状态属性设置为待处理,当它等于 -1 时表示状态未设置为待处理,然后因为 1 是正确且优越的,那么具有待处理状态的项目将首先出现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM