Creating new array from existing array javasrcipt

In JavaScript, you can create a new array from an existing array using various methods. 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 = originalArray.concat([4, 5]);
    console.log(newArray); // [1, 2, 3, 4, 5]

    The concat() method creates a new array by concatenating the original array with one or more additional arrays or values.

  3. Using the map() method:

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

    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 out elements that do not meet a certain condition.

  5. Using the reduce() method:

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

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

  6. Using the Array.from() method:

    const originalArray = [1, 2, 3];
    const newArray = Array.from(originalArray, x => x * 2);
    console.log(newArray); // [2, 4, 6]

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

These are just a few examples of how you can create a new array from an existing array in JavaScript. The choice of method depends on the specific use case and the desired outcome.