javascript 배열 값 중복 체크하기

zioni·2022년 7월 22일
0

Javascript

목록 보기
4/6
  1. indexOf
  • 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환합니다.
  • 배열.indexOf('배열에서 찾을요소',검색시작할 인덱스)
  • lastIndexOf()는 문자열에서 탐색하는 문자열이 마지막으로 등장하는 위치에 대한 index를 반환
let pizza = ['tomato', 'cheese', 'onion','olive','tomato','beef'];

 pizza.indexOf('tomato') // 0
 pizza.indexOf("tomato",3) // 4
 pizza.indexOf("apple") // -1

 pizza.lastIndexOf("tomato") // 4

중복되는 값 제거하고 문자열 반환하기

let pasta = ['tomato', 'basil', 'onion','chicken'];

let pizza = ['tomato', 'cheese', 'onion','olive','beef'];

let food = pasta.concat(pizza)
let foods = food.filter((el,index)=> {
  console.log(food.indexOf(el),index)
  food.indexOf(el)===index})
  • concat으로 배열을합치면 "tomato"가 중복되는걸 볼수 있다.
  • filter함수 안에서 indexOf를 사용해 "tomato"를 제거했다.
  • 이해 안되면 console.log()로 확인해보기!!
    0 0
    1 1
    2 2
    3 3
    0 4 -> "tomato"인덱스가 0으로 index불일치!(제거)
    5 5
    2 6
    7 7
    8 8
  1. charAt()
  • charAt 은 문자열에서 지정된 위치에 존재하는 문자를 찾아서 반환하는 함수입니다.
const str = "HELLO WORLD";
const res = str.charAt(0); // H

const hi = "HELLO WORLD";
const hires = str.charAt(str.length-1); // D
  1. Set 객체로 중복값제거
  • Set은 중복을 허용하지 않는 값을 모아놓은 Collection 객체입니다.
  • Set 객체는 new 연산자를 사용하여 생성하고, 파라미터로 iterable 객체를 전달합니다.
const set = new Set([1,2,3,4,5,6])
 set.size // 6 배열의 길이 
 set.has(3)// true 존재여부 
 set.add(7) // 추가가능
 set.delete(1) //삭제가능
 set.clear()// 전부삭제
let pasta = ['tomato', 'basil', 'onion','chicken'];

let pizza = ['tomato', 'cheese', 'onion','olive','beef'];

let food = pasta.concat(pizza)
const foods = new Set(food)
foods.size // 7 
  • 중복제거로 const foods =['tomato', 'basil', 'onion','chicken','cheese','olive','beef']

0개의 댓글