扁平化数组

  1. Object.assign(Array.prototype, {
  2. // 扁平化数组
  3. myFlat() {
  4. return this.reduce( (res, cur) =>{
  5. return Array.isArray(cur) ? res.concat(cur.myFlat()) : res.concat(cur)
  6. },[])
  7. }
  8. })
  9. let arr = [1, [2, [3, 4], 5], 6]
  10. console.log(arr.myFlat())

数组去重

  1. Object.assign(Array.prototype, {
  2. // 数组去重
  3. unique(){
  4. let newArr = [this[0]];
  5. for(let i=1; i<this.length; i++){
  6. if(newArr.indexOf(this[i]) === -1){
  7. newArr.push(this[i])
  8. }
  9. }
  10. return newArr;
  11. }
  12. })
  13. let arr2 = [1,2,2,3,4,4,5]
  14. console.log(arr2.unique())

冒泡排序(bubbleSort)

冒泡排序是最慢的排序算法。在实际运用种它是效率最低的算法!O(n^ 2)

  1. <script type="module">
  2. Object.assign(Array.prototype, {
  3. // 冒泡排序
  4. bubbleSort(){
  5. for(let i=0, len=this.length; i<len; i++){
  6. const left = this[i-1];
  7. const right = this[i];
  8. if(left > right){
  9. this[i-1] = right;
  10. this[i] = left;
  11. i = 0
  12. }
  13. }
  14. return this;
  15. }
  16. })
  17. let arr3 = [3,5,6,2,1,4]
  18. console.log(arr3.bubbleSort())
  19. </script>

快速排序(quickSort)

快速排序比大部分排序算法都要快、但是对于内存非常有限的机器来说、他不太适合!

  1. <script type="module">
  2. Object.assign(Array.prototype, {
  3. // 快速排序
  4. quickSort(){
  5. if(this.length <= 1) return this;
  6. const pivotIndex = Math.floor(this.length/2);
  7. const pivot = this.splice(pivotIndex, 1)[0];
  8. const left = [];
  9. const right = [];
  10. for(let i=0; i<this.length; i++){
  11. let v = this[i];
  12. if(v <= pivot){
  13. left.push(v)
  14. }else{
  15. right.push(v)
  16. }
  17. }
  18. return left.quickSort().concat([pivot], right.quickSort())
  19. }
  20. })
  21. let arr4 = [3,5,6,2,1,4]
  22. console.log(arr4.quickSort())
  23. </script>

插入排序(insertSort)

插入排序通过把序列中的值插入一个已经排序改的序列中、知道改序列的结束!插入排序是对冒泡排序的改进、他比冒泡排序快二倍、一般用于数据低于1000的场景下使用、或者重复排序超过200数据项的序列

  1. <script type="module">
  2. Object.assign(Array.prototype, {
  3. // 插入排序
  4. insertSort(){
  5. const _searchIndex = function(arr, x){
  6. if(x <= arr[0]) return 0;
  7. if(x >= arr[arr.length-1]) return arr.length;
  8. let i = 0;
  9. for(; i<arr.length; i++){
  10. if(arr[i] <= x && x <= arr[i + 1]){
  11. break;
  12. }
  13. }
  14. return i + 1;
  15. }
  16. let sortArr = [this[0]];
  17. for(let i=1; i<this.length; i++){
  18. let index = _searchIndex(sortArr, this[i]);
  19. sortArr.splice(index, 0, this[i]);
  20. }
  21. return sortArr;
  22. }
  23. })
  24. let arr4 = [3,5,6,2,1,4]
  25. console.log(arr4.insertSort())
  26. </script>

斐波那契数列

  1. function getFibonacci(n){
  2. const arr = [];
  3. for(let i=0; i<n-1; i++){
  4. if(i<=1){
  5. arr.push(1)
  6. }else{
  7. arr.push(arr[i-1] + arr[i-2])
  8. }
  9. }
  10. return arr;
  11. }
  12. console.log(getFibonacci(10))