05_JavaScript: Array

05_JavaScript: Array

builtin function - push, length, forEach, map, indexOf, findIndex, find, filter, splice, slice, shift, pop, unshift, concat, join, some, every, reduce

·

6 min read

  • Array is almost the same as List

Ex01. Array

const array = [1, 2, 3, 4, 5];
const animals = [{ name: 'dog' }, { name: 'cat' }];
console.log(animals); //[{ name: 'dog' }, { name: 'cat' }]
console.log(animals[0]); //{ name: 'dog' }
console.log(animals[1]); //{ name: 'cat' }

Ex02.push()

const animals = [{ name: 'dog' }, { name: 'cat' }];
animals.push({ name: 'turtle' });
console.log(animals); //[{ name: 'dog' }, { name: 'cat' }, { name: 'turtle' }];

Ex03. length

const animals = [{ name: 'dog' }, { name: 'cat' }];
console.log(animals.length); //2

animals.push({ name:'turtle' });
console.log(animals.length); //3

forEach & map

Ex04. forEach()

  • change the array
const animals = ['dog', 'cat', 'turtle'];

//Ex01
for (let i = 0; i<animals.length; i++) {
    console.log(animals[i]);
]

//Ex02. callback function
animals.forEach(animal => {
    console.log(animal);
});

Ex05. map()

  • make a new array
const array = [1, 2, 3, 4, 5, 6, 7];
const squared = [];

//Ex01
for(let i=0; i<array.length; i++) {
    squared.push(array[i] * array[i]);
}
console.log(squared);

//Ex02. forEach
array.forEach(n => {
    squared.push(n * n);
});
console.log(squared);

//Ex03. map
const square = n => n * n;
const squared = array.map(square);
console.log(squared);

//Ex04. map : shorter version
const squared = array.map(n => n * n);
console.log(squared);

Ex05-1. map() vs from()

  • Both make a new array
const arr = [0, 1, 2];
const usingFrom = Array.from(arr, (item)=> item + 1);
const usingMap = arr.map((item) => item + 1);
console.log(usingFrom); // [1, 2, 3];
console.log(usingMap); // [1, 2, 3];
// from()
// 1. 문자열을 배열로 만드는 예시
console.log(Array.from("Hello"));
// [ 'H', 'e', 'l', 'l', 'o' ]

// 2. 유사 배열 객체를 배열로 만드는 예시
console.log(Array.from({ 0: "찬민", 1: "희진", 2: "태인", length: 3 }));
// [ '찬민', '희진', '태인' ]

// 3. 함수의 매개변수들을 순서대로 배열로 만드는 예시
const funcA = (...arguments) => {
    return Array.from(arguments)
}

console.log(funcA(1,2,3,4,5));
// [ 1, 2, 3, 4, 5 ]

// 4. 새로운 배열 - 첫번째 인자로 배열, 두번재 인자로 함수
console.log(Array.from([1, 2, 3], x => x + x));
//[2, 4, 6]

With array-like and iterable

  • from() can be used with array-like and iterable objects.

  • map() cannot be used with array-like and iterable objects.

// from()
const obj = {'0':'apple', '1':'banana', '2':'carrot', length: 3}; // array-like
const objArr = Array.from(obj);
console.log(objArr); // ["apple", "banana", "carrot"]

const str = "abcde"; // iterable
const strArr = Array.from(str);
console.log(strArr); // ["a", "b", "c", "d", "e"];
// map()
const obj = {'0':'apple', '1':'banana', '2':'carrot', length: 3};
const objArr = obj.map(); // Uncaught TypeError: obj.map is not a function

const str = "abcde";
const strArr = str.map(); // Uncaught TypeError: str.map is not a function
  • length 속성을 가진 객체를 넣어주게 되면 value가 undefined이며, 길이가 5인 유사 배열이 탄생

  • **Array.from([1, 2, 3], x => x + x)**는 Array.from([1, 2,3]).map(v => v + v) 같다. 당연히 value 뿐만 아니라 index마저 사용이 가능

// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]

//Ex. 0 으로 초기환된 20x10 짜리 2차원 배열을 리턴
Array.from(
  {length: 20}, // 1부터 20까지의 배열 만들기 배열
  () => Array(10).fill(0) // 각각의 요소에 0을 채워줌 
);

Find the particular index number & values

Ex06. indexOf() : find the particular index

  • only for number / string / boolean
const animals = ['dog', 'cat', 'turtle'];
const index = animals.indexOf('dog'); 
console.log(index); //0

Ex07. findIndex() & find()

  • for object / array

  • 조건 만족하는 거 하나 찾으면 작동을 멈춤

const todos = [
  {
    id: 1,
    text: '자바스크립트 입문',
    done: true
  },
  {
    id: 2,
    text: '함수 배우기',
    done: true
  },
  {
    id: 3,
    text: '객체와 배열 배우기',
    done: true
  },
  {
    id: 4,
    text: '배열 내장함수 배우기',
    done: false
  }
];

//findIndex : return the index number
const index = todos.findIndex(todo => todo.id === 3); 
console.log(index); //2

//find : return the object
const todo = todos.find(todo => todo.id === 3);
console.log(todo); //{id: 3, text: "객체와 배열 배우기", done: true}

Ex08. filter()

  • 조건 만족하는 모든 값을 찾음

  • 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환

      const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    
      const result = words.filter(word => word.length > 6);
    
      console.log(result);
      // Expected output: Array ["exuberant", "destruction", "present"]
    
const todos = [
  {
    id: 1,
    text: '자바스크립트 입문',
    done: true
  },
  {
    id: 2,
    text: '함수 배우기',
    done: true
  },
  {
    id: 3,
    text: '객체와 배열 배우기',
    done: true
  },
  {
    id: 4,
    text: '배열 내장함수 배우기',
    done: false
  }
];

const tasksNotDone = todos.filter(todo => todo.done === false);
console.log(tasksNotDone); //[{id: 4, text: '배열 내장 함수 배우기', done: false}];

Delete the particular one : splice / slice

Ex09. splice(index, num)

const numbers = [10, 20, 30, 40];
const index = numbers.indexOf(30); //2
numbers.splice(index, 1); //index부터 1개 지우기 
console.log(numbers); //[10, 20, 40]

Ex10. slice(first, last)

const numbers = [10, 20, 30, 40];
const sliced = numbers.slice(0, 2); //from 0 to 1

console.log(sliced); // [10, 20]
console.log(numbers); // [10, 20, 30, 40]

Ex11. shift()- delete and get the first one at the same time

  • <-> unshift() - add and get the first one
const numbers = [10, 20, 30, 40];
const value = numbers.shift();
console.log(value); //10
console.log(numbers); //[20, 30, 40]
const numbers = [10, 20, 30, 40];
const value = numbers.unshift(5);
console.log(value); //5
console.log(numbers); //[5, 10, 20, 30, 40]

Ex12. pop() - delete and get the last one at the same time

  • <-> push() - add and get the last one
const numbers = [10, 20, 30, 40];
const value = numbers.pop();
console.log(value); //40
console.log(numbers); //[10, 20, 30]
const numbers = [10, 20, 30, 40];
const value = numbers.push(5);
console.log(value); //5
console.log(numbers); //[10, 20, 30, 40, 5]

Merge arr1 & arr2

Ex13. concat

  • don't change arr1 & arr2
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const concated = arr1.concat(arr2);
console.log(concated); //[1, 2, 3, 4, 5, 6];

Ex14. join

  • merge arr1 and arr2 + change into string
const array = [1, 2, 3, 4, 5];
console.log(array.join()); // 1,2,3,4,5
console.log(array.join(' ')); // 1 2 3 4 5
console.log(array.join(', ')); // 1, 2, 3, 4, 5

Ex15. some()

const fruits = ['apple', 'banana', 'strawberry'];
const result = fruits.some((fruit) => fruit === 'watermelon');
console.log(result); // false : check all the fruits and if there is 'watermelon' in fruits, it'll be true

Ex16.every()

const fruits = ['apple', 'banana', 'strawberry'];
const result = fruits.every((fruit) => fruit === 'watermelon');
console.log(result); //false : every elements have to be 'watermelon'

Ex17. reduce

4 parameters

  • acc (누적 값)

  • cur (현재 값)

  • idx (현재 인덱스)

  • src (원본 배열)

// 누적합 구하기
const numbers = [1,2,3,4,5,6,7];
const result1 = numbers.reduce((acc, cur) => acc + cur); // acc을 리턴 
const result2 = numbers.reduce((acc, cur, idx, src) => {
    console.log('acc: ', acc, 'cur: ', cur, 'idx: ', idx);
    return acc + cur;
}, 0); // 누적값 초기값을 0으로 세팅
console.log(result1);
console.log(result2);
// 평균 계산
const numbers = [1,2,3,4,5];
let sum = numbers.reduce((accumulator, current, index, array) => {
    if (index === array.length - 1) {
        return (accumulator + current) / array.length;
    }
    return accumulator + current;
}, 0);

console.log(sum);

cf. https://learnjs.vlpt.us/basics/09-array-functions.html

cf. https://ko.javascript.info/array

cf. https://velog.io/@sj_dev_js/JavaScript-Array.from-%EA%B3%BC-Array.prototype.map-%EB%B9%84%EA%B5%90%ED%95%98%EA%B8%B0

cf. https://mine-it-record.tistory.com/621