Skip to content

Instantly share code, notes, and snippets.

@uladzislau-stuk
Last active July 4, 2019 08:59
Show Gist options
  • Save uladzislau-stuk/9bcf7487125318589d909c679f7c0d11 to your computer and use it in GitHub Desktop.
Save uladzislau-stuk/9bcf7487125318589d909c679f7c0d11 to your computer and use it in GitHub Desktop.
[Hacks for Creating JavaScript Arrays] #js #hacks
// MORE THAN ONE ARGUMENTS:
// Creates a new array with the arguments as items.
// The length of the array is set to the number of arguments.
var array1 = new Array(1, 2, 3);
console.log(array1); // [1, 2, 3]
console.log(array1.length); // 3
Object.getOwnPropertyNames(array1); // ["0", "1", "2", "length"]
// ONLY ONE(NUMBER) ARGUMENT:
// Creates an array with length set to the number.
// The number must be a positive integer otherwise an error will be thrown.
// Note that the array has no property keys apart from length.
var array2 = new Array(3);
console.log(array2); // Array(3) {length: 3}
console.log(array2.length); // 3
Object.getOwnPropertyNames(array2); // ["length"]
// ONLY ONE(NON-NUMBER) ARGUMENT:
// Creates a new array with the argument as the only item.
// The length of the array is set to 1.
var array3 = new Array("3");
console.log(array3); // ["3"]
console.log(array3.length); // 1
// Using Array.prototype.fill()
// The fill() method fills all the elements of an array from a start index to an end index with a static value
var array1 = Array(3).fill(5);
array1; // ["5", "5", "5"]
var array1 = Array(3).fill();
array1; // [undefined, undefined, undefined]
// Using Array.from()
// The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object
var array1 = Array.from(new Array(3));
array1; // [undefined, undefined, undefined]
// Using the Spread Operator
var array1 = [...new Array(3)];
array1; // [undefined, undefined, undefined]
// Using Array.of()
var array1 = Array.of(5); // [5]
var array2 = Array(5); // Array(5) {length: 5}
// CLONING ARRAYS: SHALLOW COPY - HACKS
// slice()
// concat()
// Array.from()
var array1 = [1, 2, 3];
var array2 = Array.from(array1); // clone array1, shallow copy
// Destructuring
var array1 = [1, 2, 3];
var [...array2] = array1; // shallow copy
// Demonstration shallow copy
var array1 = [1, 2, 3, [1, 9 , 10]];
var array2 = Array.from(array1);
// Remove last item from the 3th item of array1
// will also be removed last item array2
array1[3].pop(); // 10
array2 // [1, 2, 3, [1, 9]];
// CLONING ARRAYS: DEEP COPY - HACKS
// Using Lodash library
// jQuery.extend
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment