猿问

如何对从AJAX调用返回的数据进行分组?

我在sharepoint中创建了一个列表,用于收集用户信息。每个条目都有日期。某些日子有很多条目。我的目标是创建一个具有日期的选择菜单。当我单击菜单时,将填充日期,但它们会重复。如何将它们作为单个值返回?


我试图嵌套另一个for循环和if语句。


$.ajax({

   url:url,

   method:'GET',

   headers:{ 'Accept': 'application/json; odata=verbose' },

   success: function(data){

     var dat = data.d.results;

      for (var i = 0;i < dat.length; i++){

    html+='<optionvalue='+itm.dateVal+'>'+itm.dateVal+'</option>';

       }     $('#week-selector').append(html);

   },

   error: function(e){

    console.log('error:'+e);

   }            

});

我得到的输出是:


3/3/2019

3/3/2019

3/3/2019

3/3/2019

3/6/2019

3/6/2019

3/10/2019

3/10/2019

我想得到的输出是:


3/3/2019

3/6/2019

3/10/2019


侃侃尔雅
浏览 154回答 3
3回答

MM们

您可以使用Set删除重复的值,然后将其转换回数组:var arr = [&nbsp; &nbsp; "3/3/2019",&nbsp; &nbsp; "3/3/2019",&nbsp; &nbsp; "3/3/2019",&nbsp; &nbsp; "3/3/2019",&nbsp; &nbsp; "3/6/2019",&nbsp; &nbsp; "3/6/2019",&nbsp; &nbsp; "3/10/2019",&nbsp; &nbsp; "3/10/2019"];console.log(Array.from(new Set(arr)));// ["3/3/2019", "3/6/2019", "3/10/2019"]```

慕的地6264312

您可以轻松编写过滤器函数以获取不同的值。var arr = ["3/3/2019","3/3/2019","3/3/2019","3/3/2019","3/6/2019","3/6/2019","3/10/2019","3/10/2019"];var distinctDates = arr.filter(function(val, idx, self){ return self.indexOf(val) === idx; });console.log(distinctDates);在ES6中,您可以按以下方式进行操作var arr = ["3/3/2019","3/3/2019","3/3/2019","3/3/2019","3/6/2019","3/6/2019","3/10/2019","3/10/2019"];var distinctDates = [...new Set(arr)];console.log(distinctDates);

烙印99

var arr = ['3/3/2019','3/3/2019','4/4/2019']arr.filter(function(item,i){return arr.indexOf(item)== i;})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答