Create a new array from an array javascript

There are several ways to create a new array from an existing array in JavaScript. Here are a few examples:

  1. Using the slice() method:

    const originalArray = [1, 2, 3, 4, 5];
    const newArray = originalArray.slice();
    console.log(newArray); // [1, 2, 3, 4, 5]

    The slice() method creates a shallow copy of the original array.

  2. Using the concat() method:

    const originalArray = [1, 2, 3];
    const newArray = [].concat(originalArray);
    console.log(newArray); // [1, 2, 3]

    The concat() method creates a new array by concatenating the original array with an empty array.

  3. Using the map() method:

    const originalArray = [1, 2, 3];
    const newArray = originalArray.map(x => x);
    console.log(newArray); // [1, 2, 3]

    The map() method creates a new array by applying a transformation function to each element of the original array.

  4. Using the filter() method:

    const originalArray = [1, 2, 3, 4, 5];
    const newArray = originalArray.filter(x => x % 2 === 0);
    console.log(newArray); // [2, 4]

    The filter() method creates a new array by filtering the original array based on a condition.

  5. Using the reduce() method:

    const originalArray = [1, 2, 3, 4, 5];
    const newArray = originalArray.reduce((acc, current) => acc.concat([current]), []);
    console.log(newArray); // [1, 2, 3, 4, 5]

    The reduce() method creates a new array by reducing the original array to a single value, which can then be converted to an array.

Note that some of these methods may create a shallow copy of the original array, while others may create a new array with the same elements but with different references.