https://stackoverflow.com/questions/931872/what-s-the-difference-between-array-and-while-declaring-a-javascript-ar
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://medium.com/@gamshan001/javascript-deep-copy-for-array-and-object-97e3d4bc401a
Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array’s length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.
JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array’s length property minus 1. Using an invalid index number returns undefined.
1 2 3 4 |
var arr = ['this is the first element', 'this is the second element', 'this is the last element']; console.log(arr[0]); // logs 'this is the first element' console.log(arr[1]); // logs 'this is the second element' console.log(arr[arr.length - 1]); // logs 'this is the last element' |
functions are all in Array.prototype
In your browser’s console, type Array.prototype and press Enter. You’ll be able to see all the functionalities used.
Create an Array
1 2 |
var fruits = ['Apple', 'Banana']; console.log(fruits.length); // 2 |
Access (index into) an Array item
1 2 |
var first = fruits[0]; // Apple var last = fruits[fruits.length - 1]; // Banana |
Loop over an Array
1 2 3 4 5 6 |
fruits.forEach(function(item, index, array) { console.log(item, index); }); // Apple 0 // Banana 1 |
Add to the end of an Array
1 2 |
var newLength = fruits.push('Orange'); // ["Apple", "Banana", "Orange"] |
Remove from the end of an Array
1 2 |
var last = fruits.pop(); // remove Orange (from the end) // ["Apple", "Banana"]; |
Remove from the front of an Array
1 2 |
var first = fruits.shift(); // remove Apple from the front // ["Banana"]; |
Add to the front of an Array
1 2 |
var newLength = fruits.unshift('Strawberry') // add to the front // ["Strawberry", "Banana"]; |
Find the index of an item in the Array
1 2 3 4 5 |
fruits.push('Mango'); // ["Strawberry", "Banana", "Mango"] var pos = fruits.indexOf('Banana'); // 1 |
Remove an item by index position
1 2 |
var removedItem = fruits.splice(pos, 1); // this is how to remove an item // ["Strawberry", "Mango"] |
Remove items from an index position
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']; console.log(vegetables); // ["Cabbage", "Turnip", "Radish", "Carrot"] var pos = 1, n = 2; var removedItems = vegetables.splice(pos, n); // this is how to remove items, n defines the number of items to be removed, // from that position(pos) onward to the end of array. console.log(vegetables); // ["Cabbage", "Carrot"] (the original array is changed) console.log(removedItems); // ["Turnip", "Radish"] |
Copy an Array
1 2 |
var shallowCopy = fruits.slice(); // this is how to make a copy // ["Strawberry", "Mango"] |
How to copy array
The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.
1 2 3 4 5 6 7 8 9 10 |
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slice(2)); // expected output: Array ["camel", "duck", "elephant"] console.log(animals.slice(2, 4)); // expected output: Array ["camel", "duck"] console.log(animals.slice(1, 5)); // expected output: Array ["bison", "camel", "duck", "elephant"] |
The code above creates clone of the original array; keep in mind that if objects exist in your array, the references are kept; i.e. the code above does not do a “deep” clone of the array contents.
…various ways
ref – https://www.briangonzalez.org/post/copying-array-javascript
There are many ways to copy an array in JavaScript, and with ES6, that list has grown even longer.
Here are some options I came up with (with the help of Twitter). They are shown in order of performance.
1 2 3 4 5 6 7 8 9 10 |
const names = [ 'Jon', 'Jacob', 'Jeff' ] const copy1 = names.slice() const copy2 = [].concat(names) const copy3 = Object.values(names) const copy4 = [...names] const copy5 = Array.of(...names) const copy6 = JSON.parse(JSON.stringify(names)) const copy7 = names.map(i => i) const copy8 = Object.assign([], names) |
It is helpful to clearly distinguish an array index from an object property name.
All indexes are property names…
but only property names that are integers between 0 and 2^32–1 are indexes
All arrays are objects, and you can create properties of any name on them.
If you use properties that are array indexes, however, arrays have the special
behavior of updating their length property as needed.
Note that you can index an array using numbers that are negative or that are not integers.
When you do this, the number is converted to a string, and that string is used as
the property name.
Since the name is not a non-negative integer, it is treated as a regular
object property, not an array index. Also, if you index an array with a string that happens
to be a non-negative integer, it behaves as an array index, not an object property.
The same is true if you use a floating-point number that is the same as an integer:
1 2 3 |
a[-1.23] = true; // This creates a property named "-1.23" a["1000"] = 0; // This the 1001st element of the array a[1.000] // Array index 1. Same as a[1] |
Another example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
let arr = new Array(); arr[0] = "ricky"; arr[1] = "bob"; arr[2] = "grandma"; arr[3] = "grandpa"; arr[4] = "shark"; arr["hobbies"] = "badminton, hill climbing, etc"; arr["lastName"] = "Tsao"; arr[-1.23] = "decimal"; arr[true] = "DESTROY" arr[false] = "CREATE" console.log(arr); // array object with properties and values. ints are considered indexes. Others are properties. console.log(arr.length); // 5. only values associated with indexes are counted |
output:
[ ‘ricky’,
‘bob’,
‘grandma’,
‘grandpa’,
‘shark’,
hobbies: ‘badminton, hill climbing, etc’,
lastName: ‘Tsao’,
‘-1.23’: ‘decimal’,
true: ‘DESTROY’,
false: ‘CREATE’ ]
5
The fact that array indexes are simply a special type of object property name means
that JavaScript arrays have no notion of an “out of bounds” error. When you try to
query a nonexistent property of any object, you don’t get an error, you simply get
undefined. This is just as true for arrays as it is for objects:
a = [true, false]; // This array has elements at indexes 0 and 1
a[2] // => undefined. No element at this index.
a[-1] // => undefined. No property with this name.
Array Literal
1 2 3 4 5 6 |
var cars = ["Saab", "Volvo", "BMW"]; // array literal console.log(cars[2]); // BMW console.log(cars[3]); // undefined cars["dealership"] = "longo, CA" console.log(cars); |
output:
BMW
undefined
[ ‘Saab’, ‘Volvo’, ‘BMW’, dealership: ‘longo, CA’ ]
What’s the real difference between declaring an array like this
var myArray = new Array();
vs
var myArray = [];
The difference between creating an array with the implicit array and the array constructor is subtle but important.
When you create an array using
1 |
var a = []; |
You’re telling the interpreter to create a new runtime array (Array specs created at runtime). No extra processing necessary at all. Done.
If you use:
1 |
var a = new Array(); |
You’re telling the interpreter, I want to call the constructor “Array” and generate an object. It then looks up through your execution context to find the constructor to call, and calls it, creating your array.
If you do not redefine Array, then its not a problem. However, if someone decides to redefine it and implement the constructor, then everything goes haywire:
1 2 3 4 5 6 7 8 9 10 11 |
function Array() { this.is = 'SPARTA'; } var a = new Array(); var b = []; alert(a.is); // => 'SPARTA' alert(b.is); // => undefined a.push('Woa'); // => TypeError: a.push is not a function b.push('Woa'); // => 1 (OK) |
In other words, the difference is that using the new operator causes the interpreter to take all sorts of extra steps to go to the global scope, look for the constructor, call the constructor and assign the result… which in the majority case is going to be a a runtime array. You can avoid the overhead of looking for the global constructor by just using []. It may seem small, but when you’re shooting for near real-time performance in your app, it can make a difference.
other examples:
1 2 |
var a = [], // these are the same b = new Array(), // a and b are arrays with length 0 |
1 2 |
c = ['foo', 'bar'], // these are the same d = new Array('foo', 'bar'), // c and d are arrays with 2 strings |
Performance Hit
https://jsperf.com/create-an-array-of-initial-size/2
Looks like creating literal array, using a while loop to initialize it, is the fastest among browsers.
1 2 3 4 5 |
var i = size; arr = []; while (i-- > 0) { arr[i] = undef; } |
For loop with push, is another good alternative
1 2 3 4 |
arr = []; for (var i = 0; i < size; ++i) { arr[i] = undef; } |
Deep Cloning
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//Deep Clone let a = [{ x:{z:1} , y: 2}]; // array with an object // that object has property x, which is another object // property y, which is integer 2 // let's deep clone a, and have b reference it let b = JSON.parse(JSON.stringify(a)); // we get an array back. // For the first element in array b, we access x, then z, and assign it 0 b[0].x.z=0 console.log(JSON.stringify(a)); //[{"x":{"z":1},"y":2}] console.log(JSON.stringify(b)); // [{"x":{"z":0},"y":2}] |
sort
1 |
const points = [40, 100, 1, 5, 25, 10]; |
if comparison is + (say, 100 – 40) do sort (if comparing 100, 40, it will sort to 40, 100)
if comparison is – (say, 40 – 100) DO NOT sort. leave as is.
So if we we get [100, 40]. 100 – 40 = 60. truthy, sort it. [40,100]
if we get [4, 20]. 4 – 20 = -16. falsey. don’t sort it. [4,20]
In the end, we get smallest to largest.
1 2 3 4 |
points.sort(function(a, b) { console.log(a, b); return a-b }); |
What if we want to sort largest to smallest?
so in comes [100(a),40(b)], we don’t want to sort in this situation and hope for a false.
So we say b-a. 40 – 100 = -60 don’t sort
in comes [40(a), 100(b)], we want to sort this, and try to give it a truthy. b-a, 100 – 40 = 60.
Now, we get largest to smallest.