• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

I’m sure everyone has a file like util.js in their project. This is a tool function that I often use in my project, but now I use the loDash plugin directly for convenience, which is convenient for rapid development.

Check whether it is an array

const isArray = (v) => {
  return v instanceof Array || v.constructor === Array || Object.prototype.toString.call(v) == '[object Array]';
}
Copy the code

Checks if a value is in an array

const inArray = (needle, haystack) => { if (! isArray(haystack)) { throw Error('the second argument is not a Array'); } let len = haystack.length; for (let i = 0; i < len; i++) { if (haystack[i] === needle) return true; } return false; }Copy the code

Check if there are any duplicate values in the array

const arrayIsRepeat = (arr) => {
    let hash = {};
    for (var i in arr) {
    if (hash[arr[i]]) {
        return true;
    }
    hash[arr[i]] = true;
    }
    return false;
}
Copy the code

test

let arr = [
    {
        a:1
    },
    {
        a:1
    },
    {
        b:1
    }
]
let newArr = arrayIsRepeat(arr);
console.log(newArr)
Copy the code

The test results

true
Copy the code

Array to heavy

const arrayUnique = (arr = []) => { if (arr.constructor ! == Array) { throw Error('arrayUnique argument is not a Array'); } let o = {}, r = []; for (let i = 0; i < arr.length; i++) { if (arr[i].constructor === Object || arr[i].constructor === Array) { if (! o[JSON.stringify(arr[i]).toString()]) { o[JSON.stringify(arr[i]).toString()] = true; r.push(arr[i]); } } else { if (! o[arr[i]]) { o[arr[i]] = true; r.push(arr[i]); } } } return r; }Copy the code

Testing:

let arr = [
	{
            a:null
	},
        {
            a: 1
	},
	{
            b: 2
	},
	{
            b: 2
	},
	{
            c: 3
	}
]
let newArr = arrayUnique(arr);
console.log(newArr)
Copy the code

The test results

Count the number of occurrences of elements in the array

function countOccurrences(arr, value) {
    return arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
}
Copy the code

Number of occurrences of detection values

const allEqual = arr => arr.every(val => val === arr[0]);

allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true

Copy the code

Other types of arrays

const castArray = val => (Array.isArray(val) ? val : [val]);
Copy the code

Specifies the depth flattening array

const flatten = (arr, depth = 1) => arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);
Copy the code

Find the intersection in an array

const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); };
Copy the code