xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js array sort All In One

js array sort All In One

Javascript sort array of objects

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

      const paths = [...svgDOM.querySelectorAll('path')];
      paths.sort((p1, p2) => {
        const bbox1 = p1.getBBox();
        const bbox2 = p2.getBBox();
        return bbox1.width * bbox1.height > bbox2.width * bbox2.height ? -1 : 1;
      }).forEach((path) => {
        const pathData = path.getAttribute('d');
        const path_points = pathDataToPolys(pathData, {tolerance:1, decimals:1});
        log(`path_points`, path_points);
      });

sort calback

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

asc / ascending

升序

[...events].sort((a, b) => (a - b > 0) ? 1 : -1);



const arr = [4,5,8,2,3];
arr.sort((a, b) => (a - b > 0) ? 1 : -1);
// [2, 3, 4, 5, 8]

desc / descending

降序

[...events].sort((a, b) => (a - b > 0) ? -1 : 1);


const arr = [4,5,8,2,3];
arr.sort((a, b) => (a - b > 0) ? -1 : 1);
// [8, 5, 4, 3, 2]

https://www.w3schools.com/js/js_array_sort.asp

leetcode

  1. Kth Largest Element in a Stream

https://leetcode.com/problems/kth-largest-element-in-a-stream/submissions/

class KthLargest {
  constructor(k, nums) {
    this.k = k;
    this.nums = nums;
  };
  add(val) {
    this.nums.push(val);
    const arr = this.nums.sort((a, b) => a - b > 0 ? -1 : 1);
    return arr[k - 1];
    // return [...new Set(arr)][k - 1];
  }
}

demos

js custom array sort

type JSONValue = null | boolean | number | string | JSONValue[] | { [key: string]: JSONValue };
type Fn = (value: JSONValue) => number

function sortBy(arr: JSONValue[], fn: Fn): JSONValue[] {
  return arr.sort((a, b) => fn(a) - fn(b) > 0 ? 1 : -1);
};


// arr = [5, 4, 1, 2, 3]
// arr.sort((a,b) => a - b > 0 ? 1 : -1);
//升序 ascending

https://leetcode.com/problems/sort-by/?envType=study-plan-v2&envId=30-days-of-javascript

svg

rect to polygon points

https://codepen.io/xgqfrms/pen/vYOWjYr

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2020-03-08 02:32  xgqfrms  阅读(165)  评论(7编辑  收藏  举报