unique() for arrays in javascript

As everybody knows there's no built-in function to remove the duplicates from an array in javascript. I've noticed this is also lacking in jQuery (which has a unique function for DOM selections only), and the most common snippet I found checks the entire array and a subset of it for each element (not very efficient I think), like: for (var i = 0; i < arr.length; i++) for (var j = i + 1; j < arr.length; j++) if (arr[i] === arr[j]) //whatever so I made my own: function unique (arr) { var hash = {}, result = []; for (var i = 0; i < arr.length; i++) if (!(arr[i] in hash)) { //it works with objects! in FF, at least hash[arr[i]] = true; result.push(arr[i]); } return result; } I wonder if there's any other algorithm accepted as the best for this case (or if you see any obvious flaw that could be fixed), or, what do you do when you need this in javascript (I'm aware that jQuery is not the only framework and some others may have this already covered).
Do these array contain only scalar values, or is there a chance that it will contain objects and arrays?

以上就是unique() for arrays in javascript的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准