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

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

问题描述

请告诉我,任何好的算法/ code摆脱阵列及其阵列中发生计唯一值的列表。 (我使用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(n 2 )的复杂性,这肯定不是最快的算法,但会为小无序阵列做的工作。

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天全站免登陆