Rahul  Gandhi

Rahul Gandhi

1584979860

10 Ways to Clone an Array in JavaScript

JavaScript provides several methods to copy, clone, or duplicate arrays and objects.

In this tutorial, we would love to share with you the simplest, different and easiest way to copy, clone or duplicate an array and objects.

1. Spread Operator (Shallow copy)

Ever since ES6 dropped, this has been the most popular method. It’s a brief syntax and you’ll find it incredibly useful when using libraries like React and Redux.

numbers = [1, 2, 3];
numbersCopy = [...numbers];

Note: This doesn’t safely copy multi-dimensional arrays. Array/object values are copied by reference instead of by value.

This is fine

numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// numbers is left alone

This is not fine

nestedNumbers = [[1], [2]];
numbersCopy = [...nestedNumbers];

numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// They've both been changed because they share references

2. Good Old for() Loop (Shallow copy)

I imagine this approach is the least popular, given how trendy functional programming’s become in our circles.

Pure or impure, declarative or imperative, it gets the job done!

numbers = [1, 2, 3];
numbersCopy = [];

for (i = 0; i < numbers.length; i++) {
  numbersCopy[i] = numbers[i];
}

Note: This doesn’t safely copy multi-dimensional arrays. Since you’re using the = operator, it’ll assign objects/arrays by reference instead of by value.

This is fine

numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// numbers is left alone

This is not fine

nestedNumbers = [[1], [2]];
numbersCopy = [];

for (i = 0; i < nestedNumbers.length; i++) {
  numbersCopy[i] = nestedNumbers[i];
}

numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// They've both been changed because they share references

3. Good Old while() Loop (Shallow copy)

Same as for—impure, imperative, blah, blah, blah…it works! ?

numbers = [1, 2, 3];
numbersCopy = [];
i = -1;

while (++i < numbers.length) {
  numbersCopy[i] = numbers[i];
}

Note: This also assigns objects/arrays by reference instead of by value.

This is fine

numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// numbers is left alone

This is not fine

nestedNumbers = [[1], [2]];
numbersCopy = [];

i = -1;

while (++i < nestedNumbers.length) {
  numbersCopy[i] = nestedNumbers[i];
}

numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// They've both been changed because they share references

4. Array.map (Shallow copy)

Back in modern territory, we’ll find the map function. Rooted in mathematics, map is the concept of transforming a set into another type of set, while preserving structure.

In English, that means Array.map returns an array of the same length every single time.

To double a list of numbers, use map with a double function.

numbers = [1, 2, 3];
double = (x) => x * 2;

numbers.map(double);

What about cloning??

True, this article’s about cloning arrays. To duplicate an array, just return the element in your map call.

numbers = [1, 2, 3];
numbersCopy = numbers.map((x) => x);

If you’d like to be a bit more mathematical, (x) => x is called identity. It returns whatever parameter it’s been given.

map(identity) clones a list.

identity = (x) => x;
numbers.map(identity);
// [1, 2, 3]

Note: This also assigns objects/arrays by reference instead of by value.

5. Array.filter (Shallow copy)

This function returns an array, just like map, but it’s not guaranteed to be the same length.

What if you’re filtering for even numbers?

[1, 2, 3].filter((x) => x % 2 === 0);
// [2]

The input array length was 3, but the resulting length is 1.

If your filter’s predicate always returns true, however, you get a duplicate!

numbers = [1, 2, 3];
numbersCopy = numbers.filter(() => true);

Every element passes the test, so it gets returned.

Note: This also assigns objects/arrays by reference instead of by value.

6. Array.reduce (Shallow copy)

I almost feel bad using reduce to clone an array, because it’s so much more powerful than that. But here we go…

numbers = [1, 2, 3];

numbersCopy = numbers.reduce((newArray, element) => {
  newArray.push(element);

  return newArray;
}, []);

reduce transforms an initial value as it loops through a list.

Here the initial value is an empty array, and we’re filling it with each element as we go. That array must be returned from the function to be used in the next iteration.

Note: This also assigns objects/arrays by reference instead of by value.

7. Array.slice (Shallow copy)

slice returns a shallow copy of an array based on the provided start/end index you provide.

If we want the first 3 elements:

[1, 2, 3, 4, 5].slice(0, 3);
// [1, 2, 3]
// Starts at index 0, stops at index 3

If we want all the elements, don’t give any parameters

numbers = [1, 2, 3, 4, 5];
numbersCopy = numbers.slice();
// [1, 2, 3, 4, 5]

Note: This is a shallow copy, so it also assigns objects/arrays by reference instead of by value.

8. JSON.parse and JSON.stringify (Deep copy)

JSON.stringify turns an object into a string.

JSON.parse turns a string into an object.

Combining them can turn an object into a string, and then reverse the process to create a brand new data structure.

Note: This one safely copies deeply nested objects/arrays!

nestedNumbers = [[1], [2]];
numbersCopy = JSON.parse(JSON.stringify(nestedNumbers));

numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);

// [[1], [2]]
// [[1, 300], [2]]
// These two arrays are completely separate!

9. Array.concat (Shallow copy)

concat combines arrays with values or other arrays.

[1, 2, 3].concat(4); // [1, 2, 3, 4]
[1, 2, 3].concat([4, 5]); // [1, 2, 3, 4, 5]

If you give nothing or an empty array, a shallow copy’s returned.

[1, 2, 3].concat(); // [1, 2, 3]
[1, 2, 3].concat([]); // [1, 2, 3]

Note: This also assigns objects/arrays by reference instead of by value.

10. Array.from (Shallow copy)

This can turn any iterable object into an array. Giving an array returns a shallow copy.

numbers = [1, 2, 3];
numbersCopy = Array.from(numbers);
// [1, 2, 3]

Note: This also assigns objects/arrays by reference instead of by value.

Conclusion

Well, this was fun ?

I tried to clone using just 1 step. You’ll find many more ways if you employ multiple methods and techniques.

#javascript #array #webdev

What is GEEK

Buddha Community

10 Ways to Clone an Array in JavaScript
Lowa Alice

Lowa Alice

1624388400

JavaScript Arrays Tutorial. DO NOT MISS!!!

Learn JavaScript Arrays

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=oigfaZ5ApsM&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=4
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#arrays #javascript #javascript arrays #javascript arrays tutorial

Terry  Tremblay

Terry Tremblay

1602154740

Fill and Filter in Array in JavaScript

By the word Array methods, I mean the inbuilt array functions, which might be helpful for us in so many ways. So why not just explore and make use of them, to boost our productivity.

Let’s see them together one by one with some amazing examples.

Array.fill():

The _fill()_ method changes all elements in an array to a static value, from a start index (default _0_) to an end index (default _array.length_). It returns the modified array.

In simple words, it’s gonna fill the elements of the array with whatever sets of params, you pass in it. Mostly we pass three params, each param stands with some meaning. The first param value: what value you want to fill, second value: start range of index(inclusive), and third value: end range of index(exclusive). Imagine you are going to apply this method on some date, so that how its gonna look like eg: array.fill(‘Some date’, start date, end date).

NOTE: Start range is inclusive and end range is exclusive.

Let’s understand this in the below example-

//declare array
var testArray = [2,4,6,8,10,12,14];

console.log(testArray.fill("A"));

When you run this code, you gonna see all the elements of testArray will be replaced by 'A' like [“A”,"A","A","A","A","A","A"].

#javascript-tips #array-methods #javascript-development #javascript #arrays

6 Ways to Add Items to an Array in JavaScript

There are various ways to add or append an item to an array. We will make use of pushunshiftspliceconcatspread and index to add items to array. Let’s discuss all the 6 different methods one by one in brief.

The push() method

This method is used to add elements to the end of an array. This method returns the new array length.

const movies = ['Avengers', 'Iron-man', 'Thor'];

const newLength = movies.push('Hulk'); 

console.log(movies); // ['Avengers', 'Iron-man', 'Thor', 'Hulk'];

console.log(newLength); //4

We can also add multiple values with push method.

const movies = ['Iron-man', 'Thor']; 

movies.push('Avengers', 'Deadpool', 'Hulk');

console.log(movies); 
// ["Iron-man", "Thor", "Avengers", "Deadpool", "Hulk"]

The unshift() method

The unshift() method is used to add elements at the beginning of an array. This method returns the new array length.

const cars = ['Audi', 'BMW', 'Jaguar']; 

const newLength = cars.unshift('Mercedes'); 
console.log(newLength ); // 4 
console.log(cars); // ['Mercedes', 'Audi', 'BMW', 'Jaguar']

We can also add multiple values with unshift() method.

const cars = ['Audi', 'Jaguar']; 

cars.unshift('Mercedes', 'Tesla'); 
console.log(cars); // ['Mercedes', 'Tesla', 'Audi', 'Jaguar']

#arrays #web-development #javascript-tips #javascript #javascript-development

Cayla  Erdman

Cayla Erdman

1597470780

A quick guide to JavaScript Arrays

Introduction

Arrays are a structure common to all programming languages so knowing what they are and having a firm grasp on what you’re able to accomplish with Arrays will take you a long way in your journey as a software developer. The code examples I share in this post will be in JavaScript but the concepts are common among all languages. What you learn here can easily be translated to any other language you work with.

In this post I’ll be covering how to perform the create, read update and delete operations using arrays, some common functions that come with the Array prototype and also how to implement them.


What is an Array

Before we jump into the juicy bits of Arrays, lets quickly gloss over what they are. Arrays

  • are a fundamental data type in JavaScript
  • are an ordered collection of values called **elements **that are stored at and accessed via an index
  • are untyped, meaning that the elements of an array could be of different types. This allows us to create complex arrays such as an array of objects or even an array of arrays (multidimensional arrays)
  • can have elements that are constants or expressions
  • have a property called length that tells you the number of elements in the array
  • inherit properties from Array.prototype that includes a wide variety useful functions that can be called from arrays or array-like objects

CRUD operations using Arrays

If you’re not familiar with the term CRUD it stands for Create, Read, Update and Delete. In this section we’ll go through each one of these operations and cover different ways you can perform each one.

Creating Arrays

There are several ways you can create an Array but the most common ways are by using

  • the Array literal syntax
  • the Array constructor i.e. new Array()

Lets take a look at each one with examples

Array literal

The array literal is the most common way of creating an array. It uses the square brackets as a notion of a container followed by comma separated values inside the square brackets. The following examples show how to use the array literal syntax and how arrays are untyped i.e. can contain elements of different types.

Image for post

Examples of untyped arrays in JavaScript created with the array literal syntax.

Array constructor

Another way to create an array is through the Array constructor.

const myArray = new Array();

Using the Array constructor, as shown above, is the same as creating an array with the array literal syntax. i.e.

// The following two lines behave exactly the same way i.e. both create an empty arrays

const myArray = new Array();
const myOtherArray = [];

The array constructor, however, is able to receive arguments that allow it to behave in different ways depending on the number and type of arguments passed to it.

  • You can pass a single numeric argument which creates an array of the specified length. This option is mostly used when you know how many elements you’ll be placing in the array
const myArray = new Array(5);

Note: If you want to define the array with a specified size, as shown above, the argument passed must be a numeric value. Any other type would be considered as the first element that’ll be placed in the array.

  • Or you can pass two or more arguments or a non-numeric argument to place the values inside the array. This works the same way as shown in the array literal examples.

Image for post

Examples of arrays created by using the Array constructor in JavaScript

As stated earlier, these two ways are the most common ways of creating arrays that you’ll see and use 99% of the time. There are a few other ways but we won’t dive deep into how they work. They are

  • the spread operator const someArray = […someOtherArray]
  • the static method Array.of()
  • and the static method Array.from()

#javascript #web-development #javascript-tips #javascript-development #javascript-arrays #sql

Rahul  Gandhi

Rahul Gandhi

1584979860

10 Ways to Clone an Array in JavaScript

JavaScript provides several methods to copy, clone, or duplicate arrays and objects.

In this tutorial, we would love to share with you the simplest, different and easiest way to copy, clone or duplicate an array and objects.

1. Spread Operator (Shallow copy)

Ever since ES6 dropped, this has been the most popular method. It’s a brief syntax and you’ll find it incredibly useful when using libraries like React and Redux.

numbers = [1, 2, 3];
numbersCopy = [...numbers];

Note: This doesn’t safely copy multi-dimensional arrays. Array/object values are copied by reference instead of by value.

This is fine

numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// numbers is left alone

This is not fine

nestedNumbers = [[1], [2]];
numbersCopy = [...nestedNumbers];

numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// They've both been changed because they share references

2. Good Old for() Loop (Shallow copy)

I imagine this approach is the least popular, given how trendy functional programming’s become in our circles.

Pure or impure, declarative or imperative, it gets the job done!

numbers = [1, 2, 3];
numbersCopy = [];

for (i = 0; i < numbers.length; i++) {
  numbersCopy[i] = numbers[i];
}

Note: This doesn’t safely copy multi-dimensional arrays. Since you’re using the = operator, it’ll assign objects/arrays by reference instead of by value.

This is fine

numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// numbers is left alone

This is not fine

nestedNumbers = [[1], [2]];
numbersCopy = [];

for (i = 0; i < nestedNumbers.length; i++) {
  numbersCopy[i] = nestedNumbers[i];
}

numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// They've both been changed because they share references

3. Good Old while() Loop (Shallow copy)

Same as for—impure, imperative, blah, blah, blah…it works! ?

numbers = [1, 2, 3];
numbersCopy = [];
i = -1;

while (++i < numbers.length) {
  numbersCopy[i] = numbers[i];
}

Note: This also assigns objects/arrays by reference instead of by value.

This is fine

numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// numbers is left alone

This is not fine

nestedNumbers = [[1], [2]];
numbersCopy = [];

i = -1;

while (++i < nestedNumbers.length) {
  numbersCopy[i] = nestedNumbers[i];
}

numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// They've both been changed because they share references

4. Array.map (Shallow copy)

Back in modern territory, we’ll find the map function. Rooted in mathematics, map is the concept of transforming a set into another type of set, while preserving structure.

In English, that means Array.map returns an array of the same length every single time.

To double a list of numbers, use map with a double function.

numbers = [1, 2, 3];
double = (x) => x * 2;

numbers.map(double);

What about cloning??

True, this article’s about cloning arrays. To duplicate an array, just return the element in your map call.

numbers = [1, 2, 3];
numbersCopy = numbers.map((x) => x);

If you’d like to be a bit more mathematical, (x) => x is called identity. It returns whatever parameter it’s been given.

map(identity) clones a list.

identity = (x) => x;
numbers.map(identity);
// [1, 2, 3]

Note: This also assigns objects/arrays by reference instead of by value.

5. Array.filter (Shallow copy)

This function returns an array, just like map, but it’s not guaranteed to be the same length.

What if you’re filtering for even numbers?

[1, 2, 3].filter((x) => x % 2 === 0);
// [2]

The input array length was 3, but the resulting length is 1.

If your filter’s predicate always returns true, however, you get a duplicate!

numbers = [1, 2, 3];
numbersCopy = numbers.filter(() => true);

Every element passes the test, so it gets returned.

Note: This also assigns objects/arrays by reference instead of by value.

6. Array.reduce (Shallow copy)

I almost feel bad using reduce to clone an array, because it’s so much more powerful than that. But here we go…

numbers = [1, 2, 3];

numbersCopy = numbers.reduce((newArray, element) => {
  newArray.push(element);

  return newArray;
}, []);

reduce transforms an initial value as it loops through a list.

Here the initial value is an empty array, and we’re filling it with each element as we go. That array must be returned from the function to be used in the next iteration.

Note: This also assigns objects/arrays by reference instead of by value.

7. Array.slice (Shallow copy)

slice returns a shallow copy of an array based on the provided start/end index you provide.

If we want the first 3 elements:

[1, 2, 3, 4, 5].slice(0, 3);
// [1, 2, 3]
// Starts at index 0, stops at index 3

If we want all the elements, don’t give any parameters

numbers = [1, 2, 3, 4, 5];
numbersCopy = numbers.slice();
// [1, 2, 3, 4, 5]

Note: This is a shallow copy, so it also assigns objects/arrays by reference instead of by value.

8. JSON.parse and JSON.stringify (Deep copy)

JSON.stringify turns an object into a string.

JSON.parse turns a string into an object.

Combining them can turn an object into a string, and then reverse the process to create a brand new data structure.

Note: This one safely copies deeply nested objects/arrays!

nestedNumbers = [[1], [2]];
numbersCopy = JSON.parse(JSON.stringify(nestedNumbers));

numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);

// [[1], [2]]
// [[1, 300], [2]]
// These two arrays are completely separate!

9. Array.concat (Shallow copy)

concat combines arrays with values or other arrays.

[1, 2, 3].concat(4); // [1, 2, 3, 4]
[1, 2, 3].concat([4, 5]); // [1, 2, 3, 4, 5]

If you give nothing or an empty array, a shallow copy’s returned.

[1, 2, 3].concat(); // [1, 2, 3]
[1, 2, 3].concat([]); // [1, 2, 3]

Note: This also assigns objects/arrays by reference instead of by value.

10. Array.from (Shallow copy)

This can turn any iterable object into an array. Giving an array returns a shallow copy.

numbers = [1, 2, 3];
numbersCopy = Array.from(numbers);
// [1, 2, 3]

Note: This also assigns objects/arrays by reference instead of by value.

Conclusion

Well, this was fun ?

I tried to clone using just 1 step. You’ll find many more ways if you employ multiple methods and techniques.

#javascript #array #webdev