[hand tearing code series] JS implementation of ten common array methods

[hand tearing code series] JS implementation of ten common array methods (I)

🚀 Easy to understand implementation methods to help us understand the corresponding methods
📚 Collect this series, and the basic advanced level is correct
🎉 This series is constantly updated. Welcome to check it out Online address

Write in front

The code implementation series is the first series related to handwritten code.
No matter how many knowledge points are summarized, it is inseparable from thinking and practice. Otherwise, it is a castle in the air. The sequence of this series is from shallow to deep. Welcome to communicate and discuss ~

1, chunk

Split the array into multiple size blocks and form a new array. If the array cannot be divided into all equal length blocks, the last remaining elements will form a block.

1.1 parameters

  • array (Array): the array to be processed
  • [size=1] (number): the length of each array block

1.2 return

  • (Array): returns a new array containing split blocks (Note: equivalent to a two-dimensional Array).

1.3 implementation

const _chunk = function (array, size = 1) {
    const length = array == null ? 0 : array.length;
    if (!length || size < 1) return [];

    const len = Math.ceil(length / size);
    const result = new Array(len);
    let index = -1;

    while (++index < len) {
        const start = size * index;
        result[index] = array.slice(start, size + start)
    }
    return result;
}

1.4 testing

const arr = ['a', 'b', 'c', 'd']
_chunk(arr, 2);
// => [['a', 'b'], ['c', 'd']]
 
_chunk(arr, 3);
// => [['a', 'b', 'c'], ['d']]

2, concat

Create a new array and concatenate array with any array or value.

2.1 parameters

  • array (Array): connected array.
  • values: the value of the connection.

2.2 return value

  • (Array): returns a new array after connection.

2.3 realization

const _concat = function (array, ...values) {
    const result = [...array];
    values.forEach(val => {
        if (Array.isArray(val)) {
            result.push(...val);
        } else {
            result.push(val);
        }
    })
    return result;
}

2.4 testing

var array = [1];
var other = _concat(array, 2, [3], [[4]]);
 
console.log(other);
// => [1, 2, 3, [4]]
 
console.log(array);
// => [1]

3, difference

Creates an array with unique array values, each value not contained in other given arrays. Returns a new array of filters

3.1 parameters

  • array (Array): the filtered array..
  • [values] (... Array): excluded values.

3.2 return value

  • (Array): returns a new array of filtered values.

3.3 realization

const _difference = (array, diff = []) => {
    if (!diff.length || !array.length) return [...array];

    return array.filter((val) => !diff.includes(val));
};

3.4 testing

_difference([3, 2, 1], [4, 2]);
// => [3, 1]

4, fill

Use the value value to fill (replace) the array, starting at the start position and ending at the end position (but excluding the end position).

Note: this method will change the array

4.1 parameters

  • array (Array): the array to be filled with changes.
  • Value (*): the value filled into the array.
  • [start=0] (number): start position (default 0).
  • [end=array.length] (number): end position (default array.length).

4.2 return value

  • (Array): returns array.

4.3 realization

const _fill = (array = [], value, start = 0, end = array.length) => {
    const { length } = array;
    // Empty array
    if (!length) return array;
    // boundary
    const ends = end > length ? length : end;
    if (start > end) return array;

    for (let i = start; i < ends; i++) {
        array[i] = value;
    }

    return array;
};

4.4 testing

const array = [1, 2, 3];
_fill(array, "a");
// => ['a', 'a', 'a']

_fill(Array(3), 2);
// => [2, 2, 2]

_fill([4, 6, 8, 10], "*", 1, 3);
// => [4, '*', '*', 10]

5, Flatten depth

Recursively traverses the array according to a specified depth, and combines all elements with the elements in the traversed sub array into a new array.

5.1 parameters

  • Depth (Number): Specifies the structure depth of the nested array to be extracted. The default value is 1.

5.2 return value

  • (Any): returns the value of the first element of the array that passes the test (judgment in the function).

5.3 realization

// Yu Guang
Array.prototype._flattenDepth = function (depth = 1) {
    // Get caller
    let arr = this;
    // Leveling layer verification
    if (depth < 1) return arr;

    return arr.reduce(
        (prev, next, i, n) => [
            ...prev,
            ...(Array.isArray(next) ? next._flattenDepth(depth - 1) : [next]),
        ],
        []
    );
};

5.4 testing

const res = [[1], [[2]]];
console.log(res.flat(1))
// => [1, [2]]
console.log(res.flat(2))
// => [1, 2]

6, join

Converts all elements in the array to separator delimited strings.

6.1 parameters

  • array (Array): the array to convert.
  • [separator = ','] (string): separate elements.

6.2 return value

  • (string): returns the connection string.

6.3 realization

const _join = (array, separator = ",") => {
    return array.reduce((prev, next) => {
        return prev ? prev + separator + next : prev + next;
    }, "");
};

6.4 testing

_join(['a', 'b', 'c'], '~');
// => 'a~b~c'

7, pop

Deletes the last element of the array and returns the deleted element.

**Note: * * this method changes the length of the array!

7.1 return value

  • (any): returns the deleted element.

7.2 realization

const _pop = function (array) {
    const result = array[array.length - 1];
    array.length - 1;
    return result;
}

7.3 testing

const sites = ['Google', 'Runoob', 'Taobao', 'Zhihu', 'Baidu'];
 
console.log(pop(sites));
// The output result is: "Baidu"
 
console.log(sites);
// The output result is: [Google ',' runoob ',' Taobao ',' Zhihu ']

8, push

Adds a new item to the end of the array and returns the new length.

8.1 parameters

  • array (Array): the array to be changed
  • value1... valueX: (required) the item to add.

8.2 return value

  • (Number): returns the new length of the array

8.3 realization

const _push = function (array, ...params) {
    const len = array.length;
    for (let i = 0; i < params.length; i++) {
        array[len + i] = params[i]
    }
    return array.length;
};

8.4 testing

const arr = [1, 2, 3];
_push(arr, 4);
console.log(arr)
// => [1, 2, 3, 4]

9, remove

Remove all elements in the array whose callback returns true value, and return the array composed of removed elements.

Note: unlike filter, this method will change the array.

9.1 parameters

  • array (Array): connected array.
  • callback (function): judgment function.

9.2 return value

  • (Array): returns a new array composed of removed elements.

9.3 realization

const _remove = function(array, callback) {
    const result = [];
    if (!(array != null && array.length)) {
        return result;
    }
    const { length } = array;
    let i = -1;
    const ids = [];
    while (++i < length) {
        const value = array[i];
        if (callback(value, i, array)) {
            result.push(value);
        }
    }

    for (let i = 0; i < result.length; i++) {
        const index = array.indexOf(result[i]);
        array.splice(index, 1);
    }
    return result;
};

9.4 testing

const array = [1, 2, 3, 4];
const evens = _remove(array, (n, i) => !(n % 2));

console.log(array);
// => [1, 3]

console.log(evens);
// => [2, 4]

10, reverse

Invert the array so that the first element becomes the last element, the second element becomes the penultimate element, and so on.

**Note: * * this method will change the original array based on Array#reverse.

10.1 parameters

  • array (Array): the array to modify.

10.2 return

  • (Array): returns array

10.3 realization

const _reverse = (array) => {
    for (let i = 0; i < Math.floor(array.length / 2); i++) {
        const left = i;
        const right = array.length - 1 - i;
        [array[left], array[right]] = [array[right], array[left]];
    }
    return array;
};

10.4 testing

const array = [1, 2, 3];
 
_reverse(array);
 
console.log(array);
// => [3, 2, 1]

Write at the end

That's all for the first part of this series. Interested friends can leave a message to discuss better code implementation and other code implementations they want to know. The next part of the hand tearing code series will be methods related to other data types. Don't lose it

Other series

Keywords: Javascript Front-end

Added by pellky on Sat, 18 Dec 2021 11:27:08 +0200