【问题标题】:Using a callback to remove duplicate items from an array使用回调从数组中删除重复项
【发布时间】:2017-11-29 05:48:00
【问题描述】:

我被困在这个问题上,要求从数组中删除重复值。以下是说明:

编写一个名为 uniq 的函数,它接收一个数组和一个回调函数。 从数组中删除所有重复值,并以修改后的数组作为参数调用回调。

【问题讨论】:

  • 我们很乐意帮助您解决问题,但是:“请求家庭作业帮助的问题必须包括您迄今为止为解决问题所做的工作摘要,并且描述您在解决它时遇到的困难。”
  • 嗨@Brittany,很抱歉,但在 Stackoverflow 上,您应该提供一个您尝试过的示例:-|
  • 这里已经回答了:stackoverflow.com/questions/9229645/…

标签: javascript arrays callback


【解决方案1】:
function myFunction(myArray, callBack){

 var unique = myArray.filter(function(item, pos) {
   //validates whether the first occurrence of current item in array
   // equals the current position of the item (only return those items) 
   return myArray.indexOf(item) == pos;
 });

 //wrap your result and pass to callBack function 
 callBack(unique);

}

使用

调用你的函数
myFunction([1,2,2,4,5], function(result){
console.log(result);
})

或者

function callBack(result){console.log(result);} 
myFunction([1,2,2,3,4], callBack);

【讨论】:

    猜你喜欢
    • 2012-12-06
    • 2012-03-25
    • 2012-08-05
    • 2011-06-29
    • 2011-01-04
    相关资源
    最近更新 更多