DEV Community

Dahye Ji
Dahye Ji

Posted on

JavaScript Basic -Array, Object, Method

Array

It's special data structure to store ordered collections.
There are two syntaxes for creating an empty array:

let arr = new Array();
let arr = [];
Enter fullscreen mode Exit fullscreen mode

Almost all the time, the second syntax is used. We can supply initial elements in the brackets

let animals = ["Dog", "Elephant", "Fox"];
Enter fullscreen mode Exit fullscreen mode

Array elements are numbered, starting with ze.ro(index).
We can get an element by its number(index) in square brackets.

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"
Enter fullscreen mode Exit fullscreen mode

We can access to array with index and change the value like this.

animals[2] = "Giraffe"; // now ["Dog", "Elephant", "Giraffe"]
Enter fullscreen mode Exit fullscreen mode

Also can add element to array like this

animals[3] = "Lion" ; // now ["Dog", "Elephant", "Giraffe", "Lion"]
Enter fullscreen mode Exit fullscreen mode

Counting the total elements in the array

let animals = ["Dog", "Elephant", "Giraffe", "Lion"];

console.log(animal.length ); // 4
Enter fullscreen mode Exit fullscreen mode

An array can store elements of any type.

For instance:

// 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
Enter fullscreen mode Exit fullscreen mode

Array practice

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);

Enter fullscreen mode Exit fullscreen mode

Methods

pop/push, shift/unshift

pop()

pop() extracts the last element of the array and returns it.

let animals = ["Dog", "Elephant", "Giraffe", "Lion"]

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

animals; // ["Dog", "Elephant", "Giraffe"]
Enter fullscreen mode Exit fullscreen mode

push()

push() append the element to the end of the array.

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"]
Enter fullscreen mode Exit fullscreen mode

shift()

shift() extracts the first element of the array and returns it.

let animals = ["Dog", "Elephant", "Giraffe"];

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

animals; // ["Elephant", "Giraffe"]
Enter fullscreen mode Exit fullscreen mode

unshift()

unshift() adds the element to the beginning of the array.

let animals = ["Elephant", "Giraffe"];

animals.unshift("Dog");

animals; // ["Dog", "Elephant", "Giraffe"];
Enter fullscreen mode Exit fullscreen mode

Methods push and unshift can add multiple elements at once.

let animals = ["Dog"];

animals.push("Turtle", "Bear"); // 3
animals; // ["Dog", "Turtle", "Bear"];
animals.unshift("Fox", "Panda"); //5
animals; // ["Fox", "Panda", "Dog", "Turtle", "Bear"]
Enter fullscreen mode Exit fullscreen mode

toString()

Arrays have their own implementation of toString method that returns a comma-separated list of elements.

let animals = ["Fox", "Panda", "Dog", "Turtle", "Bear"];
animals.toString();
// "Fox,Panda,Dog,Turtle, Bear"
Enter fullscreen mode Exit fullscreen mode

join()

join() creates a string of array items joined.

let animals = ["Fox", "Panda", "Dog", "Turtle", "Bear"];
animals.join("!!*");
// 'Fox!!*Panda!!*Dog!!*Turtle!!*Bear'
// if it was
// animals.join("")
// it becomes 'FoxPandaaDogTurtleBear'
Enter fullscreen mode Exit fullscreen mode

split()

split() splits the string into an array by the given delimiter.

let phoneNum = "010.0000.0000";

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

phoneNum.split(".").join("-");
// '010-0000-0000'
Enter fullscreen mode Exit fullscreen mode

slice()

It returns a new array copying to it all items from index start to end (not including end). Both start and end can be negative, in that case position from array end is assumed.
Syntax

arr.slice([start], [end]);
Enter fullscreen mode Exit fullscreen mode
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()
Enter fullscreen mode Exit fullscreen mode

splice()

splice() method is like a swiss army knife for arrays. It can do everything: insert, remove and replace elements.
** Note! splice() modifies the array unlike slice()
Syntax

arr.splice(index, deleteCount, element])
Enter fullscreen mode Exit fullscreen mode

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

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"]
Enter fullscreen mode Exit fullscreen mode

** Adding/modifying multiple element in array **

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']
Enter fullscreen mode Exit fullscreen mode

Find more about splice

concat()

concat() creates a new array that includes values from other arrays and additional items.
Syntax

arr.concat(arg1, arg2...)
Enter fullscreen mode Exit fullscreen mode

It accepts any number of arguments – either arrays or values.

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
Enter fullscreen mode Exit fullscreen mode

Normally, it only copies elements from arrays.
But there are exceptions like object.. find more about concat()

sort()

It sorts the array in place, changing its element order.

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]
Enter fullscreen mode Exit fullscreen mode

reverse()

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.
Enter fullscreen mode Exit fullscreen mode
  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 “key: value” pair, where key is a string (also called a “property name”), and value can be anything.
Example of object

let person = {
  //key: value
  name: "Irene",
  age: 25,
  height: 165,
  weight: 50,
  career: { first: "sales advisor", second: "web developer" },
};
Enter fullscreen mode Exit fullscreen mode

Accessing an Object and getting property value

person.name; // dot notation - objectname.key
// "Irene"
person['name']; // bracket notation - objectname['key']
// "Irene"
Enter fullscreen mode Exit fullscreen mode

*** Be aware! ***

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"
Enter fullscreen mode Exit fullscreen mode

*** DO NOT MIX dot notation and bracket notation because it makes it confusing. It's better to stick to one. ***

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"
Enter fullscreen mode Exit fullscreen mode

Exception

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
Enter fullscreen mode Exit fullscreen mode

Object keys, values, entries

Object.keys(obj)

Object.keys(obj) returns only keys(property name) of object.

Object.keys(person);
// ["name", "age", "height", "weight", "career"]
// it returns property names of object person
Enter fullscreen mode Exit fullscreen mode

Object.values(obj)

Object.values(obj) returns only values of object.

Object.values(person);
// (['Irene', 25, 165, 50, {…}]
// it returns property values of object person
Enter fullscreen mode Exit fullscreen mode

Object.entries(obj)

Object.entries(obj) returns array of [key, value] pair of object.

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)
Enter fullscreen mode Exit fullscreen mode
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'}
Enter fullscreen mode Exit fullscreen mode

You can also write above code this way using Object.entries()

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'}
Enter fullscreen mode Exit fullscreen mode

** How to access and get values from array and object

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.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)