ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Array, Object 관련 메소드
    프로그래밍/Javascript 2021. 9. 7. 13:44

    ✔ filter

    The filter() method creates a new array with all elements that pass the test implemented by the provided function

    배열에서 특정 값을 포함한 아이템만 선택하고자 할 때 include 와 함께 사용하거나 or 특정 아이템을 제외한 나머지 리스트를 리턴할 때 or 특정 값을 가진 아이템만 배열에서 리턴할 때도 사용한다

    const newList = list.filter((item) => filtered.includes(item.xxx));
    const newList = list.filter((item) => item.id !== inputId);
    const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    const result = words.filter(word => word.length > 6);
    console.log(result); // ['exuberant', 'destruction', 'present']

     

    ✔ includes

    Array.prototype.includes()

    The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate

    특정 배열이 있는데 그 배열에 있는 아이템이 다른 배열에도 포함되었는지 확인하고 싶을 때 or 특정 배열에 있는 아이템이 map 돌리는 아이템에 포함된 내용인지 확인하고 싶을 때 사용한다

    const newList = list.filter((item) => filtered.includes(item.xxx));
    list.map((item) => {
    	if (FilteredItem.includes(item.id)) { /* 로직로직 */ }
    })
    const numArray = [1, 2, 3];
    console.log(numArray.include(2)); // true
    console.log(numArray.include("2")); // false
    
    const pets = ['cat', 'dog', 'bat'];
    console.log(pets.includes('cat')); // true
    console.log(pets.includes('at')); // false

    String.prototype.includes()

    The includes() method performs a case-sensitive search to determine whether one string may be found within another string, returning true or false as appropriate

    const sentence = 'The quick brown fox jumps over the lazy dog.';
    const word = 'fox';
    
    console.log(`The word "${word}" ${sentence.includes(word) ? 'is' : 'isn\'t'} in the sentence.`);
    // expected output: "The word "fox" is in the sentence"

     

     

    ✔ map

    The map() method creates a new array populated with the results of calling a provided function on every element in the calling array

    그래서 props 가 많은 object Array 를 map 적용해서 필요한 props 만 뽑아낸 object Array 로 새로 만들 수 있는 것

    const numArray = [1, 4, 9, 16];
    const double = numArray.map(x => x * 2);
    console.log(double); // [2, 8, 18, 32]
    list.map((item, index) => { ... /* index 관련 로직 가능 */ });

     

    ✔ concat

    The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array

    그래서 redux 에서 기존 배열 state 에 새로 들어온 배열을 추가할 때 concat 을 사용

    const movieSlice = createSlice({
       ....
        reducers: {
          getMoviesSuccess(state, action) {
           	 const movies = action.payload;
             state.movies = state.movies ? state.movies?.concat(movies) : movies;
           },
    const prevArray = ['a', 'b', 'c'];
    const nextArray = ['d', 'e', 'f'];
    const Array = prevArray.concat(nextArray);
    console.log(Array); // ['a', 'b', 'c', 'd', 'e', 'f']

     

    ✔ sort

    The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values

    날짜 정렬, 가격 정렬 등 정렬할 때 많이 쓴다

    list.sort((a, b) => {
        return filter.sort === "NEWEST" ? b.date - a.date : a.price - b.price; 
    });

     

    ✔ find

    (많이 쓰지는 않았음) The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned

    나는 typescript 사용해서 enum 선언했을 때 string 값을 enum Status 로 바꿔줄 때 사용함

    const status: Status = OPTIONS.find((option) => option === value)!;
    const numArray = [5, 12, 8, 130, 44];
    const found = numArray.find(element => element > 10);
    console.log(found); // 12

     

    - 각 array 관련 method 를 여러 번 중첩해 사용할 수 있다. .filter().sort().concat() 등등 

     

    ✔ slice

    The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. Return value: A new array containing the extracted elements

    파라미터 1개(start) 만 쓰기도, 2개 파라미터(start, end)를 넘기기도 함

    const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
    console.log(animals.slice(2)); // ['camel', 'duck', 'elephant']
    console.log(animals.slice(2, 4)); // ['camel', 'duck']
    console.log(animals.slice(1, 5)); // ['bison', 'camel', 'duck', 'elephant']
    
    console.log(animals.slice(-2)); // ['duck', 'elephant']
    console.log(animals.slice(2, -1)); // ['camel', 'duck']

    페이지네이션 할 때, 전체 데이터 중 페이지에 맞는 데이터만 state 에 넣어줄 때 사용하였음

    setCurrentMembers(members.slice(indexOfFirstPost, indexOfLastPost));

     

    ✔ splice

    The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice()

    Return value: An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned

    const months = ['Jan', 'March', 'April', 'June'];
    months.splice(1, 0, 'Feb'); // inserts at index 1
    console.log(months); // ['Jan', 'Feb', 'March', 'April', 'June']
    months.splice(4, 1, 'May'); // replaces 1 element at index 4
    console.log(months); // ['Jan', 'Feb', 'March', 'April', 'May']

     

    ✔ push

    The push() method adds one or more elements to the end of an array and returns the new length of the array

    Return value: The new length property of the object upon which the method was called 

    기존 배열에 item 을 넣어 기존 배열을 변화시킨다, 다만 push 가 리턴하는 것은 변화된 배열의 길이 이므로, return 하는 부분에 push 넣으면 안된다

    const animals = ['pigs', 'goats', 'sheep'];
    console.log(animals.push('cows')); // 4
    animals.push('cows');
    console.log(animals); // ['pigs', 'goats', 'sheep', 'cows']
    
    animals.push('chickens', 'cats', 'dogs');
    console.log(animals); // ['pigs', 'goats', 'sheep', 'cows', 'chickens', 'cats', 'dogs']

     

    ✔ some

    The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array

    있는지 없는지 테스트할 때 사용하므로, 로컬 스토리지에 해당 id 가 있는지 없는지 확인하고, 이를 boolean 변수로 해서 다음 로직을 처리할 때 사용함

    const array = [1, 2, 3, 4, 5];
    const even = (element) => element % 2 === 0; // checks whether an element is even
    console.log(array.some(even)); // true
    const findProduct = storage.some((el) => el.id === product.id);
    if (!findProduct) items.push(data);

     

    ✔ isArray

    The Array.isArray() method determines whether the passed value is an Array

    Array.isArray([1, 2, 3]); // true
    Array.isArray({ foo: 123 }); // false
    Array.isArray('foobar'); // false
    Array.isArray(undefined); // false

     

    ✔ fill

    The 

     

    참고

    더보기

     

    댓글