배열에 중복을 추가하지 않고 특정 속성에 대해 한 번에 하나의 값만 가질 수있는 방법은 무엇입니까?

아들 187

좀이 CalendarIcons링크에 그림처럼 보이는합니다.

CalendarIcon

이러한 아이콘에는 다음과 같은 ID가 있습니다.

  • autumn=2020-08-20
  • autumn=2020-08-22
  • spring=2020-04-20
  • spring=2020-04-21

날짜를 보관할 배열을 만들었습니다 const selectedDates = []. 내 상태입니다. 날짜를 선택하면 id값을 selectedDates배열 에 넣을 수 있습니다. 하나의 아이콘을 선택하면 ID autumn=2020-08-20가 표시되고 selectedDates배열로 푸시됩니다 . 그러나이 ID가있는 다른 아이콘을 클릭 autumn=2020-08-22하면 배열로 푸시됩니다. 그러나 나는 autumn중 하나만 원하고 spring배열 하나만 원합니다 . 배열에 autumn또는 값이 하나만 포함되도록 수정하려면 어떻게 spring해야합니까?

이것은 내 handleClicked 메소드입니다 CalendarIcons.

    handleClicked(calendarIconId, rowLabelId) {

    // Should not add same value autumn, spring, etc. again, and only add one value specificed behind the =
    var dateArray = this.state.selectedDates.concat(calendarIconId);

    this.setState({
        calendarSelectedIconId: calendarIconId,
        rowTracker: rowLabelId,
        selectedDates: dateArray
    });
}

질문이 명확하기를 바랍니다. 질문이 명확하지 않은 경우 의견을 보내주세요. 도와 주셔서 감사합니다!

그레고리 뉴트

Set대신 사용Array

여기에 설정에 대한 훌륭한 기사

Set자동으로 값을 고유하게 만듭니다. 다음과 같은 것을 가질 수 있습니다.

// Declaration of the Set
const uniqueSet = new Set();

function handleClicked(calendarIconId) {
  // Add the new value inside of the Set
  uniqueSet.add(calendarIconId);
  
  // Turn the set into an array
  const array = Array.from(uniqueSet);

  console.log(array);
}

handleClicked('autumn=2020-08-20');
handleClicked('autumn=2020-08-22');
handleClicked('autumn=2020-08-22');
handleClicked('autumn=2020-08-22');
handleClicked('autumn=2020-08-22');
handleClicked('autumn=2020-08-22');
handleClicked('spring=2020-04-20');
handleClicked('spring=2020-04-21');
handleClicked('spring=2020-04-21');
handleClicked('spring=2020-04-21');
handleClicked('spring=2020-04-21');
handleClicked('spring=2020-04-21');


편집 : 우리는 각 시즌에 대해 하나의 값만 유지하고 싶습니다.

// Declaration of an object. We are going to use the key/value system
const library = {};

function handleClicked(calendarIconId) {
  // We "open" the value to extract the relevant informations
  const [
    key,
    value,
  ] = calendarIconId.split('=');

  // Add the new value inside of the object
  library[key] = value;
  
  // Turn the object into an array, we gotta rebuild the values
  const array = Object.keys(library).map(x => `${x}=${library[x]}`);

  console.log(array);
}

handleClicked('autumn=2020-08-20');
handleClicked('autumn=2020-08-22');
handleClicked('autumn=2020-08-22');
handleClicked('autumn=2020-08-22');
handleClicked('autumn=2020-08-22');
handleClicked('autumn=2020-08-22');
handleClicked('spring=2020-04-20');
handleClicked('spring=2020-04-21');
handleClicked('spring=2020-04-21');
handleClicked('spring=2020-04-21');
handleClicked('spring=2020-04-21');
handleClicked('spring=2020-04-21');

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관