본문 바로가기
프론트엔드/바닐라 자바스크립트

자바스크립트 배열 개념과 APIs

by juneMiller 2021. 12. 7.
'use strict'

//Array 
//1.Declaration

const arr1 =new Array();
const arr2 =[1,2];

//2.Index position 
const fruits = ['🍎','🍌'];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
console.log(fruits[fruits.length-1]); 

//3.looping over an array
//print all fruits
//a.for
for(let i =0; i<fruits.length; i++){
    console.log(fruits[i]);
}

//b. for of
for(let fruit of fruits){
    console.log(fruit);
}

//c.forEach
fruits.forEach(function (fruit, index, array){
    console.log(fruit, index, array);
});

//d.Anonymous function you can use arrow => 
fruits.forEach((fruit) => console.log(fruit));


/* forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void;
    /**
     * Calls a defined callback function on each element of an array, and returns an array that contains the results.
     * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
     * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
     */ 


//4.Additin, deletion, copy
//push: add an item to the end
fruits.push('🍓','🍑');
console.log(fruits);

//pop: remove an item from the end
const poped = fruits.pop();
fruits.pop();
console.log(fruits);
console.log("poped " + poped);

//unshift: add an item to the benigging
//shift: remove an item from the benigging
fruits.unshift('🍓','🍋');
console.log(fruits);

//shift: remove an item from the benigging
fruits.shift();
fruits.shift();
console.log(fruits);

//note!! shift, unshift are slower than pop, push 

//remove an item by index position 
fruits.push('🍓','🍑','🍋'); 
console.log(fruits);
//fruits.splice(1);
//console.log(fruits);

fruits.splice(1,1); //how many of them do you wanna delete? 
console.log(fruits);

fruits.splice(1,1,'🍏','🍉'); //you can add where you want. 
console.log(fruits);

/* splice(start: number, deleteCount?: number): string[]
The number of elements to remove.
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
@returns — An array containing the elements that were deleted. */


//combine two arrays
const fruits2=['🍐','🥥'];
const newFruits = fruits.concat(fruits2);
console.log(newFruits);

/*concat(...items: ConcatArray<T>[]): T[];

 * Combines two or more arrays.
 * This method returns a new array without modifying any existing arrays.
 * @param items Additional arrays and/or items to add to the end of the array.
 */

//5.Searching
//find the index (includes and indexOf)
console.log(fruits);
console.log(fruits.indexOf('🍎'));
console.log(fruits.indexOf('🍉'));
console.log(fruits.includes('🍉'));
console.log(fruits.includes('🥥'));
console.log(fruits.indexOf('🥥'));

//lastIndextOf
//console.clear();
fruits.push('🍎');
console.log(fruits);
console.log(fruits.indexOf('🍎'));
console.log(fruits.lastIndexOf('🍎'));



//Quiz
//01. make a  string out of an array 
{
    const fruits = ['apple','banana', 'orange'];
    const result = fruits.join('|');
    console.log(result);
}

//02. make an array out of a string
{
    const fruits = '🍎, 🥝, 🍌, 🍒'; 
    const result = fruits.split(',', 2);
    console.log(result);
    const result2 = fruits.split(',');
    console.log(result);
}

//03.make this array look like this: [5,4,3,2,1]

{
    const array = [1,2,3,4,5];
    const result = array.reverse();
    console.log(result);

}

//04.make new array without the first two elements
{
    const array = [1,2,3,4,5];
    //const result = array.splice(0,2); // 배열 자체를 수정
    const result2 = array.slice(2,5); // 배열에서 원하는 부분만 잘라서 출력
    console.log(array)
    console.log(result2)
}

class Student { 
    constructor(name, age, enrolled, score) {
        this.name = name;
        this.age = age;
        this.enrolled =enrolled;
        this.score = score;
    }
}

const students = [
    new Student('A', '29', true, 45),
    new Student('B', '28', false, 80),
    new Student('C', '30', true, 90),
    new Student('D', '40', false, 66),
    new Student('E', '18', true, 88),
]

//05.find a student with the score 90 
/*find(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): T | undefined;

*
 * Returns the index of the first element in the array where predicate is true, and -1
 * otherwise.
 * @param predicate find calls predicate once for each element of the array, in ascending
 * order, until it finds one where predicate returns true. If such an element is found,
 * findIndex immediately returns that element index. Otherwise, findIndex returns -1.
 * @param thisArg If provided, it will be used as the this value for each invocation of
 * predicate. If it is not provided, undefined is used instead.
 */
{
    const result = students.find((student) => student.score === 90 );
        //console.log(student, index);
        
    
    console.log(result);
}

{
    //06.make an array of enrolled students 
    const result = students.filter((student) => student.enrolled);
    console.log(result);
}

/*filter(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T[];
*
 * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
 * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
 * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
 */

{
    //07.make an array containing only the students' scores
    // result should be : [45, 80, 90, 66, 88]
    const result = students.map((student) => student);
    console.log(result);

    const result2 = students.map((student) => student.score);
    console.log(result2);

    const result3 = students.map((student) => student.score * 3);
    console.log(result3);

    /*map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];
    *
     * Returns the elements of an array that meet the condition specified in a callback function.
     * @param predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
     * @param thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
     */
}

{
    //08.check if there is a student with the score lower than 50
   // const result = students.find((student) => student.score < 50);
   // console.log(result);
   const result =students.some((student) => student.score < 50);
   console.log(result); // 어떤 하나의 조건이라도 맞으면 

   const result1 = !students.every((student) => student.score >= 50);
   console.log(result1); // 모든 좋건이 맞으면 
}

{
    //09.compute student's average score 
    //reduceRight >> 순서가 꺼구로 호출 되어 누적된다. 

    /* const result = students.reduce((prev, curr) => {
        console.log('----------');
        console.log(prev);
        console.log(curr);
        //return curr;
        return prev + curr.score;
    }, 0);
    console.log(result); */

    const result = students.reduce((prev, curr) =>  prev + curr.score, 0);
    console.log(result / students.length);

    //값을 누적하기 위하 함수 
    //reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
    //reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
    /*
     * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
     * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
     * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
     */
}

{
    //10.make a string containing all the scores
    //result should be: '45,80,90,66,88'
    const result = students.map((student) => student.score).join();
    console.log(result);

    const result1 = students.map((student) => student.score)
    .filter((score) => score >= 50)
    .join();
    console.log(result1);
}

{

    //do sorted in ascending order  
    //result shoulb be: '45.66,80,88,90'
    const result = students
    .map(student => student.score)
    .sort((a,b) => a - b)
    .join();
    console.log(result);


    const result = students
    .map(student => student.score)
    .sort((a,b) => b - a)
    .join();
    console.log(result);
}