Moment For Technology

JS array common operations summary

Posted on June 23, 2022, 12:30 p.m. by 方淑慧
Category: The front end Tag: notes

The array a

  • Conventional version
function flatten(arr) {
  let res = [];
  for (let i = 0; i  arr.length; i++) {
    if (Array.isArray(arr[i])) res = res.concat(flatten(arr[i]));
    else res.push(arr[i]);
  }
  return res;
}
Copy the code
  • Reduce version
function flatten(arr) {
  return arr.reduce((acc, cur) =  {
    return Array.isArray(cur) ? acc.concat(flatten(cur)) : acc.concat(cur); } []); }Copy the code
  • Designated depth version
function flattenByDeep(arr, deep) {
  deep = deep || 1;
  let res = [];
  for (let i = 0; i  arr.length; i++) {
    if (Array.isArray(arr[i])  deep  1) {
      res = res.concat(flattenByDeep(arr[i], deep - 1));
    } else res = res.concat(arr[i]);
  }
  return res;
}
Copy the code

An array of random sequence

function flush(arr) {
  for (let i = 0; i  arr.length; i++) {
    / / Math. Floor ([0, 1) * size) =  [0, the size 1]
    let index = Math.floor(Math.random() * arr.length); [arr[i], arr[index]] = [arr[index], arr[i]]; }}Copy the code

Array to heavy

,2,2,3 [1] = [1, 2, 3]

  • Create an object to mark if the element was present
function unique(arr) {
  let container = {};
  return arr.filter(item=  {
    if (container.hasOwnProperty(item)) {
      return false;
    }
    container[item] = true;
    return true;
  });
Copy the code
  • Using the indexOf ()
function unique(arr) {
  return arr.filter((e, i) =  arr.indexOf(e) === i);
}
Copy the code
  • Using the Set ()
const unique = arr=  Array.from(new Set(arr));

const unique = arr=  [...new Set(arr)];

Copy the code

Array decrement 2 removes all duplicate values

Use indexOf() and lastIndexOf(); IndexOf() searches from the beginning, and lastIndexOf() searches from the tail

function unique(arr) {
  return arr.filter(e=  arr.indexOf(e) === arr.lastIndexOf(e));
}
Copy the code

Handwritten reduce

Array.prototype.reduce = function (fn, init) {
  let acc = init || this[0];
  let start = init ? 0 : 1;
  for (let i = start; i  this.length; i++) {
    acc = fn(acc, this[i], i, this);
  }
  return acc;
};
Copy the code
Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.