如何计算 Javascript 数组中的匹配值 [英] How to count Matching values in Array of Javascript

查看:25
本文介绍了如何计算 Javascript 数组中的匹配值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我任何好的算法/代码来从数组中获取唯一值列表及其在数组中的出现次数.(我正在使用 javascript).

please tell me any good algorithm/code to get list of unique values from array and count of its occurrence in array. (i am using javascript).

推荐答案

对于从数组中去除重复项并返回具有唯一值的新数组的方法,您可能需要检查以下 Array.unique 实现.由于 O(n2) 复杂度,它当然不是最快的算法,但可以完成小型未排序数组的工作.

For a method that will strip the duplicates from an array and returns a new array with the unique values, you may want to check the following Array.unique implementation. With an O(n2) complexity, it is certainly not the quickest algorithm, but will do the job for small unsorted arrays.

它在 GPLv3 下获得许可,所以我应该被允许在此处粘贴实现:

It is licensed under GPLv3, so I should be allowed to paste the implementation here:

// **************************************************************************
// Copyright 2007 - 2009 Tavs Dokkedahl
// Contact: http://www.jslab.dk/contact.php
//
// This file is part of the JSLab Standard Library (JSL) Program.
//
// JSL is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// any later version.
//
// JSL is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// ***************************************************************************

Array.prototype.unique =
  function() {
    var a = [];
    var l = this.length;
    for(var i=0; i<l; i++) {
      for(var j=i+1; j<l; j++) { 
        if (this[i] === this[j])  // If this[i] is found later in the array
          j = ++i;
      }
      a.push(this[i]);
    }
    return a;
  };

您可以按如下方式使用它:

You would be able to use it as follows:

var myArray = new Array("b", "c", "b", "a", "b", "g", "a", "b");
myArray.unique(); // returns: ["c", "g", "a", "b"]

您可能想要调整上面的内容,以某种方式附加每个值的出现次数.

You may want to tweak the above to somehow append the number of occurrences of each value.

这篇关于如何计算 Javascript 数组中的匹配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆