为了账号安全,请及时绑定邮箱和手机立即绑定

如何避免将重复项添加到数组中,并且特定属性一次只有一个值?

如何避免将重复项添加到数组中,并且特定属性一次只有一个值?

慕少森 2022-05-26 16:20:57
我有一些CalendarIcons看起来像链接中的图片。这些图标有这些 id:autumn=2020-08-20autumn=2020-08-22spring=2020-04-20spring=2020-04-21我创建了一个数组来保存日期:const selectedDates = []在我的状态。当我选择一个日期时,我可以将id值推送到selectedDates数组中。当我选择一个图标时,我得到 id:autumn=2020-08-20并推送到我的selectedDates数组。但是,如果我单击具有此 ID 的另一个图标:autumn=2020-08-22它也被推送到数组中。但我只想要一个autumn值,并且只想要spring我的数组中的一个值。我该如何解决,所以我的数组只包含autumnor的一个值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    });}我希望问题很清楚,如果问题不清楚,请给我反馈。感谢您的帮助!
查看完整描述

2 回答

?
Helenr

TA贡献1780条经验 获得超4个赞

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');


查看完整回答
反对 回复 2022-05-26
?
DIEA

TA贡献1820条经验 获得超3个赞

你可以做


if(!Array.includes(id)) {

  Array.push(id)

}


查看完整回答
反对 回复 2022-05-26
  • 2 回答
  • 0 关注
  • 116 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号