JavaScript Basic -Array, Object, Method
Tags: javascript, array, method, object
Published: 2021-12-02 14:59:09

#**Array**
It's special data structure to store ordered collections.
There are two syntaxes for creating an empty array:
```js
let arr = new Array();
let arr = [];
```
Almost all the time, the second syntax is used. We can supply initial elements in the brackets
```js
let animals = ["Dog", "Elephant", "Fox"];
```
Array elements are numbered, starting with ze.ro(index).
We can get an element by its number(index) in square brackets.
```js
let animals = ["Dog", "Elephant", "Fox"];

console.log(animals) // ["Dog", "Elephant", "Fox"]
console.log(animals[0]); // "Dog"
console.log(animals[1]); // "Elephant"
console.log(animals[2]); // "Fox"
```
We can access to array with index and change the value like this.
```js
animals[2] = "Giraffe"; // now ["Dog", "Elephant", "Giraffe"]
```
Also can add element to array like this
```js
animals[3] = "Lion" ; // now ["Dog", "Elephant", "Giraffe", "Lion"]
```

### Counting the total elements in the array
```js
let animals = ["Dog", "Elephant", "Giraffe", "Lion"];

console.log(animal.length ); // 4
```

### An array can store elements of any type.
For instance:
```js
// mix of values
let arr = [ "Orange", { name: "Hailey" }, true, function() { console.log("hello"); } ];

// get the object at index 1 and then show its name
console.log(arr[1].name; // "Hailey"

// get the function at index 3 and run it
arr[3](); // hello
```
### Array practice
```js
let numbers = [
  // one
  [
    [10, 20, 30, 40, 50],
    [20, 30, 40, 50, 60],
  ],
  // two
  [
    [10, 20, 30, 40, 50],
    [20, 30, 40, 50, 60],
  ],
];

// get the average number of array one from numbers array
//1.
let sum = 0;
for (let i = 0; i < 2; i++) {
  for (let j = 0; j < 5; j++) {
    sum += numbers[0][j];
  }
}
console.log(sum / 10);
//2.
let one = numbers[0][0];
let two = numbers[0][1];
let arr = one.concat(two);
let sum = 0;

for (let i of arr) {
  sum += i;
}
console.log(sum / arr.length);

```

# **Methods**
## **pop/push, shift/unshift**
###pop() 
pop() extracts the last element of the array and returns it.
```js
let animals = ["Dog", "Elephant", "Giraffe", "Lion"]

console.log(animals.pop()); // remove "Lion" and console.log it

animals; // ["Dog", "Elephant", "Giraffe"]
```


### **push()**
push() append the element to the end of the array.
```js
let animals = ["Dog", "Elephant", "Giraffe"];

animals.push("Lion"); // 4

animals; // "Dog", "Elephant", "Giraffe", "Lion"

//animals.push(...) is equal to fruits[animals.length] = ....
animals[animals.length] = "Cat";
animals // ["Dog", "Elephant", "Giraffe", "Lion", "Cat"]
```


### **shift()**
shift() extracts the first element of the array and returns it.
```js
let animals = ["Dog", "Elephant", "Giraffe"];

console.log(animals.shift()); // remove Dog and console.log it

animals; // ["Elephant", "Giraffe"]
```

### **unshift()**
unshift() adds the element to the beginning of the array.
```js
let animals = ["Elephant", "Giraffe"];

animals.unshift("Dog");

animals; // ["Dog", "Elephant", "Giraffe"];
```

###Methods push and unshift can add multiple elements at once.
```js
let animals = ["Dog"];

animals.push("Turtle", "Bear"); // 3
animals; // ["Dog", "Turtle", "Bear"];
animals.unshift("Fox", "Panda"); //5
animals; // ["Fox", "Panda", "Dog", "Turtle", "Bear"]
```

## **toString()**
Arrays have their own implementation of toString method that returns a comma-separated list of elements.
```js
let animals = ["Fox", "Panda", "Dog", "Turtle", "Bear"];
animals.toString();
// "Fox,Panda,Dog,Turtle, Bear"
```

## **join()**
join() creates a string of array items joined.
```js
let animals = ["Fox", "Panda", "Dog", "Turtle", "Bear"];
animals.join("!!*");
// 'Fox!!*Panda!!*Dog!!*Turtle!!*Bear'
// if it was
// animals.join("")
// it becomes 'FoxPandaaDogTurtleBear'
```

## **split()**
split() splits the string into an array by the given delimiter. 
```js
let phoneNum = "010.0000.0000";

phoneNum.split(".");
// (3) ['010', '0000', '0000']

phoneNum.split(".").join("-");
// '010-0000-0000'
```

## **slice()**
It <u>**returns a new array copying to it all items from index start to end (not including end)**</u>. Both start and end can be negative, in that case position from array end is assumed.
**Syntax**
```js
arr.slice([start], [end]);
```

```js
let animals = ["Fox", "Panda", "Dog", "Turtle", "Bear", "Lion"];
animals.slice(1, 4); // slice before index 4 
// ["Panda", "Dog", "Turtle"]
animals.slice(2); // copy from index 2
//  ["Dog", "Turtle", "Bear", "Lion"]
animals;
// ["Fox", "Panda", "Dog", "Turtle", "Bear", "Lion"];
// the array doesn't get affected or channged (slice doesn't change the data of array. It copies and save it to a new array)

animals.slice(-5, -2);
// ["Panda", "Dog", "Turtle"]
animals.slice(2, -1);
// ["Dog", "Turtle", "Bear"]

animals[-1];
// undefined  
// there isn't -1/negative index in javascript. However, there you can use negative index for slice()
```
## **splice()**
splice() method is like a swiss army knife for arrays. It can do everything: <u>**insert, remove and replace elements**</u>.
** **Note!** <u>_splice() modifies the array_</u> unlike slice()
**Syntax**

```js
arr.splice(index, deleteCount, element])
```
splice() **modifies** arr starting from the index start: removes deleteCount elements and then inserts element at their place. Returns the array of modified elements.
**Example**
```js
let arr = ["I", "am", "Developer"];
arr.splice(1, 1); // from index 1 remove 1 element
//["am"]
console.log(arr);
// ["I", "Developer"]

arr.splice(0,1,"Frontend");
// ["I"]
console.log(arr);
// ["Frontend", "Developer"]
```
** Adding/modifying multiple element in array **
```js
let arr = ["I", "am", "Frontend", "Developer"];

arr.splice(2,1,"an","amazing","Frontend")
// ["Frontend"] // this get removed from array and "an","amazing","Frontend" get added in index 2
console.log(arr);
// ["I", "am", "an", "amazing", "Frontend", "Developer"]

arr;
// ["I", "am", "an", "amazing", "Frontend", "Developer"]

arr.splice(3,1,"aspiring", "junior")
// ['amazing'] // element deleted from array (delete one element from index3 and add "junior" in index3) 
console.log(arr);
// ['I', 'am', 'an', 'aspiring', 'junior', 'Frontend', 'Developer']
```
[Find more about splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)

## **concat()**
concat() <u>creates a new array</u> that **includes values from other arrays** and **additional items**.
**Syntax**
```js
arr.concat(arg1, arg2...)
```
It accepts any number of arguments – either arrays or values.
```js
let arr = [1, 2];

// create an array from: arr and [3,4]
console.log(arr.concat([3, 4])); // [1,2,3,4]
arr;
// [1, 2] 
// it doesn't modify the original array. You should assign it to new variable if you'd like to save it.

// create an array from: arr and [3,4] and [5,6]
console.log(arr.concat([3, 4], [5, 6]));
// [1,2,3,4,5,6]

// create an array from: arr and [3,4], then add values 5 and 6
console.log(arr.concat([3, 4], 5, 6)); // 1,2,3,4,5,6
```
Normally, <u>**it only copies elements from arrays**</u>.
But there are exceptions like object.. find more about [concat()](arr.concat(arrayLike))

## **sort()**
It sorts the array in place, changing its element order.
```js
let data = [10, 20, 30, 11, 22, 25];
data.sort();
// [10, 11, 20, 22, 25, 30]
data;
// [10, 11, 20, 22, 25, 30]

let data = [10, 20, 30, 11, 22, 25, 111];
data.sort();
// [10, 11, 111, 20, 22, 25, 30]
// Why does 111 comes after 11? 
// Reason: It's because of ASCII order. 
// Because of that, you must specify the order if it's ascending order or descending order.
// array.sort((a,b) =>a-b); // ascending order
// array.sort(function (a, b) { // the same as above
  return a - b;
});
// array.sort((a,b => b-a); // descending order
// array.sort(function (a, b) { // the same as above
  return b - a;
});

data.sort((a, b) => a - b); // sorting it ascending order
// [10, 11, 20, 22, 25, 30, 111]

data.sort((a, b) => a - b).reverse(); // reversing them makes them descending order.
// (7) [111, 30, 25, 22, 20, 11, 10]
```

## **reverse()**
```js
let data = [10, 11, 111, 20, 22, 25, 30]
data.reverse();
// [30, 25, 22, 20, 111, 11, 10]
data;
// [30, 25, 22, 20, 111, 11, 10]

let data = [10, 20, 30, 11, 22, 25, 111];
data.reverse();
// [111, 25, 22, 11, 30, 20, 10]
// why isn't it descending order?
// because reverse() doesn't sort them in descending order. 
// reverse() just reverse them. that's it.
// if it was sorting them in descending order, 111 should come first then 30.
// it just reverse the array.
```
1. sort() is lexicographical order.
2. reverse() is not reverse and sort. It's just reverse.
sort + reversing sorted order => reversed sort
reverse => just reverse.

** If you want to sort array in descending order,
sort them first then reverse. Or **`sort((a, b) => b - a);`** which is descending order.

# **Object**
An object can be created with brackets {…} with an optional list of properties. A property is a <u>**“key: value” pair**</u>, where key is a string (also called a “property name”), and value can be anything.
Example of object
```js
let person = {
  //key: value
  name: "Irene",
  age: 25,
  height: 165,
  weight: 50,
  career: { first: "sales advisor", second: "web developer" },
};
```

## **Accessing an Object and getting property value**
```js
person.name; // dot notation - objectname.key
// "Irene"
person['name']; // bracket notation - objectname['key']
// "Irene"
```
*** **Be aware!** ***
```js
person.'name';
// Uncaught SyntaxError: Unexpected string
person[name];
// undefined
// without ''(quote), it's considered as a variable not property, and there isn't variable called name, it's undefined

person.career.first;
// "sales advisor"
```
*** **DO NOT MIX dot notation and bracket notation because it makes it confusing. It's better to stick to one.** ***
```js
person['career'].first;
// "sales advisor"
// why can't ['career'] be [carrer]?
// As it's mentioned once above, if it's written without quotation mark, it's considered as a variable NOT property name.

person['career']['first']
// "sales advisor"
```
### Exception
```js
let person = {
  name: "Irene",
  age: 25,
  height: 165,
  weight: 50,
  career: { first: "sales advisor", second: "web developer"
  10: 100,
};

person[10];
// 100
// if property is number, you can access to it without quotation. HOWEVER it's not recommended.
// DO THIS WAY.
person["10"];
// 100
```

# **Object keys, values, entries**
## **Object.keys(obj)**
Object.keys(obj) returns only keys(property name) of object.
```js
Object.keys(person);
// ["name", "age", "height", "weight", "career"]
// it returns property names of object person
```
## **Object.values(obj)**
Object.values(obj) returns only values of object.
```js
Object.values(person);
// (['Irene', 25, 165, 50, {…}]
// it returns property values of object person
```
## **Object.entries(obj)**
Object.entries(obj) returns array of [key, value] pair of object.
```js
Object.entries(person);
// [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2)]
// 0: (2) ['10', 100]
// 1: (2) ['name', '이호준']
// 2: (2) ['age', 10]
// 3: (2) ['height', 30]
// 4: (2) ['weight', 40]
// 5: (2) ['이력', {…}]
// length: 6
// [[Prototype]]: Array(0)
```
```js
let data = Object.entries(person); // if you do this you can save those key, value pair
data[0];
//  ['name', 'Irene']
data[1];
//  ['age', 25]
data[2];
// ['height', 165]
data[3];
// ['weight', 50]
...

for (let i of data) {
    console.log(i[0], i[1])
}
// name Irene
// age 25
// height 165
// weight 50
// career {first: 'sales advisor', second: 'web developer'}
```
You can also write above code this way using Object.entries()
```js
for (let [i, j] of Object.entries(person)) {
  console.log(i, j);
}
// name Irene
// age 25
// height 165
// weight 50
// career {first: 'sales advisor', second: 'web developer'}
```
** How to access and get values from array and object
```js
for (let [[i, j], k] of [
  [[1, 2], 2],
  [[1, 2], 4],
]) {
  console.log(i, j, k);
}
// Array : [value1, value2, value3]
// -> access to them using index
// [0], [1], [2], ...
// Object : [(key-value)1, (key-value)2, (key-value)3]
// -> access to them using key
//.key_name

// Object.getOwnPropertyDescriptors()
// console.log(Object.getOwnPropertyDescriptor(person, "name"));
// Object.getOwnPropertyDescriptors() method returns all own property descriptors of a given object.
```