30 seconds of code - Array learning

Posted by midi_mick on Wed, 18 Sep 2019 04:39:51 +0200

Original address: https://github.com/30-seconds...

deepFlatten

Recurses the specified array to a one-dimensional array.

Use the Array.prototype.concat() method to stitch the arrays, use the extension operator.. reduce the nesting of the arrays, and recursively loop through each array.

const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));

// own understand
const deepFlatten = arr => {
    const newArr = arr.map(v => {
        if (Array.isArray(v)) {
            // Reduce nesting under arrays by recursively calling functions on arrays
            return deepFlatten(v);
        }
        return v;
    });
    // ...reduce one level of nesting
    return [].concat(...newArr);
};

// example
deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]

difference

Returns the difference of the first array from the second.

Creating a Set-type variable for the second array reduces the time of the check and loops it using the Array.prototype.filter() method.

const difference = (a, b) => {
    const s = new Set(b);
    // Remove elements from b that do not contain a
    return a.filter(x => !s.has(x));
};

// example
difference([1, 2, 3], [1, 2, 4]); // [3]

differenceBy

After processing the two arrays with the specified function, the new arrays will be differentiated.

The process is similar to the difference method, in which the Array.prototype.map() method is used to convert the two arrays and the Array.prototype.filter() method is used to cycle through the new arrays.The final result is data that has been altered by the fn function.

const differenceBy = (a, b, fn) => {
    // Converting an array to a Set requires using functions on the array first
    const s = new Set(b.map(fn));
    // Arrays also need to be processed with functions before filtering
    return a.map(fn).filter(x => !s.has(x));
};

// example
differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1]
differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [2]

differenceWith

By using a comp comparison function, filters out arrays in the first array that cannot be compared to the second array at all as true.

Loop through the first array and check in the second if it contains elements that match the comp function. If there are no elements that match the requirements, this field in the first array is eligible for filtering.

const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);

// own understand
const differenceWith = (arr, val, comp) => {
    return arr.filter(a => {
        return val.findIndex(b => comp(a, b)) === -1;
    });
}

// example
differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2]

drop

Delete n elements from the left side of the array.

Using Array.prototype.slice() to intercept data, since only the first parameter is used, the result is to intercept n to the end of the array, which is equivalent to deleting all elements from 0 to n-1.

const drop = (arr, n = 1) => arr.slice(n);

// example
drop([1, 2, 3]); // [2,3]
drop([1, 2, 3], 2); // [3]
drop([1, 2, 3], 42); // []

dropRight

Delete n elements from the right side of the array.

Using Array.prototype.slice() to intercept data and reverse a given n, the result is actually to intercept the elements of the original array from 0 to -n, which is equivalent to deleting all elements of the array index from n to the end.

const dropRight = (arr, n = 1) => arr.slice(0, -n);

// example
dropRight([1, 2, 3]); // [1,2]
dropRight([1, 2, 3], 2); // [1]
dropRight([1, 2, 3], 42); // []

dropRightWhile

Delete elements from the end of the array until the given function returns true, and finally returns the remaining elements of the array.

Loop through the array from the end, each loop calls the given function on the element, pauses the loop only when the given function returns true, and finally intercepts the array using Array.prototype.slice().

const dropRightWhile = (arr, func) => {
    let rightIndex = arr.length;
    while (rightIndex-- && !func(arr[rightIndex]));
    return arr.slice(0, rightIndex + 1);
};

// own understand
const dropRightWhile = (arr, func) => {
    for (let rightIndex = arr.length - 1; rightIndex >= 0; rightIndex--) {
        if (func(arr[rightIndex])) {
            return arr.slice(0, rightIndex + 1);
        }
    }
    return [];
};

// example
dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]

dropWhile

Delete elements from the left side of the array until the given function returns true, and finally returns the remaining elements of the array.

Loop the left side of the array, each time a loop calls a given function on an element, pauses the loop only when the given function returns true, and finally intercepts the array using Array.prototype.slice().

const dropWhile = (arr, func) => {
    while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
    return arr;
};

// own understand
const dropWhile = (arr, func) => {
    for (let i = 0; i < arr.length; i++) {
        if (func(arr[i])) {
            return arr.slice(i);
        }
    }
    return [];
};

// example
dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]

everyNth

Given a number, loop through the elements in the array to take out the elements at the multiple of the number.

Use Array.prototype.filter() to filter out elements whose index + 1 is not zero for a given number.

const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);

// own understand
const everyNth = (arr, nth) => arr.filter((e, i) => (i + 1) % nth === 0);

// example
everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]

filterFalsy

Filter out all false values in the array.Same as the previous compact function.

Using Array.prototype.filter() filtering, the given function is the default Boolean.

const filterFalsy = arr => arr.filter(Boolean);

// example
filterFalsy(['', true, {}, false, 'sample', 1, 0]); // [true, {}, 'sample', 1]

Topics: Javascript github