項目經常使用JS方法封裝(四) [ 數組相關處理 ]

持續更新中...

封裝方法傳送門:json


使用方法很是簡單,只需放到你的 utils.js 工具文件中,直接 export const 加上個人封裝方法,在別的文件中使用{方法1,方法2,方法3...}引用後就能夠直接使用了!數組

001.冒泡排序

升序 bubbleAsSort()bash

bubbleAsSort = arr => {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = 0; j < arr.length - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        let temp = arr[j + 1];
        arr[j + 1] = arr[j];
        arr[j] = temp;
      }
    }
  }
  return arr;
}
複製代碼

降序 bubbleDeSort()函數

bubbleDeSort = arr => {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = 0; j < arr.length - 1 - i; j++) {
      if (arr[j] < arr[j + 1]) {
        let temp = arr[j + 1];
        arr[j + 1] = arr[j];
        arr[j] = temp;
      }
    }
  }
  return arr;
}
複製代碼

002.選擇排序

升序 selectAsSort()工具

selectAsSort = arr => {
  let minIndex, temp;
  for (let i = 0; i < arr.length - 1; i++) {
    minIndex = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }
    temp = arr[i];
    arr[i] = arr[minIndex];
    arr[minIndex] = temp;
  }
  return arr;
}
複製代碼

降序 selectDeSort()post

selectDeSort = arr => {
  let minIndex, temp;
  for (let i = 0; i < arr.length - 1; i++) {
    minIndex = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] > arr[minIndex]) {
        minIndex = j;
      }
    }
    temp = arr[i];
    arr[i] = arr[minIndex];
    arr[minIndex] = temp;
  }
  return arr;
}
複製代碼

003.插入排序

升序 insertAsSort()測試

insertAsSort = arr => {
  let current, preIndex;
  for (let i = 1; i < arr.length; i++) {
    current = arr[i];
    preIndex = i - 1;
    while (preIndex >= 0 && arr[preIndex] > current) {
      arr[preIndex + 1] = arr[preIndex];
      preIndex--;
    }
    arr[preIndex + 1] = current;
  }
  return arr;
}
複製代碼

降序 insertDeSort()ui

insertDeSort = arr => {
  let current, preIndex;
  for (let i = 1; i < arr.length; i++) {
    current = arr[i];
    preIndex = i - 1;
    while (preIndex >= 0 && arr[preIndex] < current) {
      arr[preIndex + 1] = arr[preIndex];
      preIndex--;
    }
    arr[preIndex + 1] = current;
  }
  return arr;
}
複製代碼

004.數組去重

arrDemp1 = arr => {
  let newArr = [];
  let m = {};
  for (let i = 0; i < arr.length; i++) {
    let n = arr[i];
    if (m[n]) {

    } else {
      newArr.push(arr[i]);
      m[n] = true;
    }
  }
  return newArr;
}

//遍歷數組法
arrDemp2 = arr => {
    let temp = [];
    for (let i = 0; i < arr.length; i++) {
        //indexOf()方法可返回某個指定的字符串或數組值在字符串或數組中首次出現的位置,若不在其中則返回-1
        if (temp.indexOf(arr[i]) === -1)
            temp.push(arr[i]);
    }
    return temp;
}

//排序法
arrDemp3 = arr => {
    let temp = [];
    arr.sort();
    temp.push(arr[0]);
    //由於數組已經通過排序,因此重複元素必定相鄰,判斷當前數組第i個元素與temp的最後一個元素是否相等,不相等時才複製元素
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] != temp[temp.length - 1])
            temp.push(arr[i]);
    }
    return temp;
}

//對象法
arrDemp4 = arr => {
    let temp = [];
    let json = {};
    //將當前數組的元素值看成對象的屬性,遍歷數組,比對對象,若是對象的這個屬性不存在則將當前數組元素複製到臨時數組,並添加該屬性且將屬性值賦值爲1
    for (let i = 0; i < arr.length; i++) {
        if (!json[arr[i]]) {//若是對象沒有該屬性
            temp.push(arr[i]);
            json[arr[i]] = 1;//添加屬性,將屬性值賦值爲1
        }
    }
    return temp;
}
複製代碼

也能夠使用ES6中的new Set,一步到位spa

let arr = [1,2,3,5,4,5,4,3,6]
let arrDemp = new Set(arr)  //arrDemp是一個對象
let newArr = [...arrDemp]   //把arrDemp轉化成數組
console.log(newArr);
複製代碼

005.數組對象去重

將對象數組中屬性相同的項去重code

/*
*   objArr 對象數組
*   para 將要進行去重的字段(String類型)
*/

測試數據:
let objArr = [{ name: 'a', age: 1 }, { name: 'a', age: 2 }, { name: 'b', age: 2 }]

console.log(objArrDemp1(objArr,'name'));    // [ { name: 'a', age: 1 }, { name: 'b', age: 2 } ]
console.log(objArrDemp1(objArr,'age'));     // [ { name: 'a', age: 1 }, { name: 'a', age: 2 } ]

objArrDemp1 = (objArr, para) => {
    let result = [];
    let temp = {};
    for (let i = 0; i < objArr.length; i++) {
        let parameter = objArr[i][para];
        if (temp[parameter]) {
            continue;//不繼續執行接下來的代碼,跳轉至循環開頭
        }
        temp[parameter] = true;//爲temp添加此屬性(parameter)且將其值賦爲true
        result.push(objArr[i]);//將這一項複製到結果數組result中去
    }
    return result;
}


objArrDemp2 = (objArr, para) => {
    let hash = {};
    //reduce方法有兩個參數,第一個參數是一個callback,用於針對數組項的操做;第二個參數則是傳入的初始值,這個初始值用於單個數組項的操做。
    objArr = objArr.reduce(function (item, next) {//這是針對數組項操做的函數,對於每一個數組項,reduce方法都會將其調用一次
        hash[next[para]] ? '' : hash[next[para]] = true && item.push(next);
        return item;
    }, []);//初始值是一個空對象,使用reduce方法返回的是空對象經過疊加執行以後的結果
    return objArr;
}
複製代碼

006.統計數組中各個元素出現的次數

staArrNum = arr => {
  let obj = {};
  for (let i = 0; i < arr.length; i++) {
    let m = arr[i];
    if (obj.hasOwnProperty(m)) {
      obj[m] += 1;
    } else {
      obj[m] = 1;
    }
  }
  return obj;
}

let arr = [1, 2, 3, 6, 5, 3, 2, 1, 2, 3, 2, 1]

console.log(staArrNum(arr));  //    { '1': 3, '2': 4, '3': 3, '5': 1, '6': 1 }
複製代碼

007.在數組中找指定的元素,返回下標

arrFinNum = function (arr,num) {
  let index = -1;
  for (let i = 0; i < arr.length; i++) {
    if (num == arr[i]) {
      index = i;
      break;
    }
  }
  return index;
}

let arr = [1,2,3,4,5,6]
console.log(arrFinNum(arr,4));  // 3
複製代碼

008.刪除數組中的元素

delArrNum = (arr,val) => {
  let index = arrFinNum(arr, val) //調用了前面自行添加的arrFinNum方法
  if (index != -1) {
    return arr.splice(index, 1);
  }
}
複製代碼

示例

let arr = [1, 2, 3, 4, 5, 6]

arrFinNum = (arr, num) => {
  let index = -1;
  for (let i = 0; i < arr.length; i++) {
    if (num == arr[i]) {
      index = i;
      break;
    }
  }
  return index;
}

delArrNum = (arr,val) => {
  let index = arrFinNum(arr, val) //調用了前面自行添加的arrFinNum方法
  if (index != -1) {
    return arr.splice(index, 1);
  }
}

console.log(delArrNum(arr,2));  //  [ 2 ]
複製代碼

009.二分查找

//非遞歸實現
binarySearch = (arr, key) => {
  let high = arr.length - 1,
    low = 0;
  while (low <= high) {
    let m = Math.floor((high + low) / 2);
    if (arr[m] == key) {
      return m;
    }
    if (key > arr[m]) {
      low = m + 1;
    } else {
      high = m - 1;
    }
  }
  return false;
}
let arr = [-1, 1, 3, 4, 5, 8, 32, 234, 12, 42];
console.log(binarySearch(arr, 4));
複製代碼
//遞歸實現
binarySearch = (arr, low, high, key) => {
  if (low > high) {
    return -1;
  }
  let mid = parseInt((high + low) / 2);
  if (arr[mid] == key) {
    return mid;
  } else if (arr[mid] > key) {
    high = mid - 1;
    return binarySearch(arr, low, high, key);
  } else if (arr[mid] < key) {
    low = mid + 1;
    return binarySearch(arr, low, high, key);
  }
};
let arr = [-1, 1, 3, 4, 5, 8, 32, 234, 12, 42];
console.log(binarySearch(arr, 0, 13, 5));
複製代碼

010.對象處理爲數組對象

/**
 *  obj 須要處理的對象
 */
objToArrObj = obj => {
  let arr = []
  for(let i in obj){
    arr.push({[i]:obj[i]})
  }
  return arr
}

//  測試數據
let obj = {20180410: 5, 20180411: 13, 20180412: 26, 20180413: 16}
console.log(objToArrObj(obj));
/*
  [
    { 20180410: 5 },
    { 20180411: 13 },
    { 20180412: 26 },
    { 20180413: 16 }
  ]
*/
複製代碼

011.經過鍵查找對象數組中對應的下標、鍵、值

/**
 *  arr 對象數組
 *  index 要查找的鍵名
 */
objArrHandle = (arr,keyName) => {
  let sub = arr.findIndex(item=>item[keyName])
  let obj = arr[sub]
  let key = Object.keys(obj)[0]
  let value = obj[Object.keys(obj)]
  return '下標:'+sub+' 鍵:'+key+' 值:'+value
}

//  測試數據
let arr = [{ 20180410: 5 },{ 20180411: 13 },{ 20180412: 26 },{ 20180413: 16 }]
console.log(objArrHandle(arr,20180412));  // 下標:2 鍵:20180412 值:26
複製代碼
相關文章
相關標籤/搜索