使用Javascript计算包含特定字符串的数组中唯一出现次数

时间:2016-06-08 17:44:23

标签: javascript arrays

这是我的javascript数组:

arr = ['blue-dots', 'blue', 'red-dots', 'orange-dots', 'blue-dots'];

使用Javascript,我如何计算包含字符串“dots”的数组中所有唯一值的总数。因此,对于上面的数组,答案是3(蓝点,橙点和红点)。

8 个答案:

答案 0 :(得分:2)

var count = 0,
    arr1 = [];    
for (var i = 0; i < arr.length; i++) {
    if (arr[i].indexOf('dots') !== -1) {
        if (arr1.indexOf(arr[i]) === -1) {
            count++;
            arr1.push(arr[i]);
        }
    }
 }

检查某个元素是否包含'dots',如果是,则检查它是否已经在arr1中,如果没有增加count,则将元素添加到arr1。

答案 1 :(得分:1)

一种方法是将元素存储为对象的键,然后获取键的计数:

var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
console.log(Object.keys(arr.reduce(function(o, x) {
  if (x.indexOf('dots') != -1) {
    o[x] = true;
  }
  return o
}, {})).length)

答案 2 :(得分:0)

this question开始,我获得了getUnique功能。

Array.prototype.getUnique = function(){
   var u = {}, a = [];
   for(var i = 0, l = this.length; i < l; ++i){
      if(u.hasOwnProperty(this[i])) {
         continue;
      }
      a.push(this[i]);
      u[this[i]] = 1;
   }
   return a;
}

然后你可以添加一个函数来计算字符串数组中字符串的出现次数:

function getOcurrencesInStrings(targetString, arrayOfStrings){
  var ocurrencesCount = 0;
  for(var i = 0, arrayOfStrings.length; i++){
    if(arrayOfStrings[i].indexOf(targetString) > -1){
      ocurrencesCount++;
    }
  }
  return ocurrencesCount;
}

然后你就是:

getOcurrencesInStrings('dots', initialArray.getUnique())

这将返回您想要的数字。

它不是最小的代码,但它具有高度可重用性。

答案 3 :(得分:0)

尝试这样的事情:

// Create a custom function
function countDots(array) {
  var count = 0;

  // Get and store each value, so they are not repeated if present.
  var uniq_array = [];
  array.forEach(function(value) {
    if(uniq_array.indexOf(value) == -1) {
      uniq_array.push(value);

      // Add one to count if 'dots' word is present.
      if(value.indexOf('dots') != -1) {
        count += 1;
      }
    }
  });

  return count;
}

// This will print '3' on console
console.log( countDots(['blue-dots', 'blue', 'red-dots', 'orange-dots', 'blue-dots']) );

答案 4 :(得分:0)

var uniqueHolder = {};
var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
arr.filter(function(item) {
    return item.indexOf('dots') > -1;
  })
  .forEach(function(item) {
    uniqueHolder[item] ? void(0) : uniqueHolder[item] = true;
  });
console.log('Count: ' + Object.keys(uniqueHolder).length);
console.log('Values: ' + Object.keys(uniqueHolder));

答案 5 :(得分:0)

[
  {
    "id": 2008588422,
    "type": "movie",
    "movie": {
      "title": "Batman v Superman: Dawn of Justice",
      "year": 2016,
      "ids": {
        "trakt": 129583,
        "slug": "batman-v-superman-dawn-of-justice-2016",
        "imdb": "tt2975590",
        "tmdb": 209112
      }
    }
  },
  {
    "id": 1995814508,
    "type": "movie",
    "movie": {
      "title": "Dirty Grandpa",
      "year": 2016,
      "ids": {
        "trakt": 188691,
        "slug": "dirty-grandpa-2016",
        "imdb": "tt1860213",
        "tmdb": 291870
      }
    }
  }
]
var arr = [ "blue-dots", "blue", "red-dots", "orange-dots", "blue-dots" ];
var fArr = []; // Empty array, which could replace arr after the filtering is done.
arr.forEach( function( v ) {
  v.indexOf( "dots" ) > -1 && fArr.indexOf( v ) === -1 ? fArr.push( v ) : null;
  // Filter if "dots" is in the string, and not already in the other array.
});

// Code for displaying result on page, not necessary to filter arr

document.querySelector( ".before" ).innerHTML = arr.join( ", " );
document.querySelector( ".after" ).innerHTML = fArr.join( ", " );

简单地说,它将循环遍历数组,如果点在字符串中,并且它在Before: <pre class="before"> </pre> After: <pre class="after"> </pre>中不存在,则会将其推入fArr,否则它什么都不做。

答案 6 :(得分:0)

试试这段代码,

arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];

sample = [];    
for (var i = 0; i < arr.length; i++) {
    if ((arr[i].indexOf('dots') !== -1) && (sample.indexOf(arr[i]) === -1)){
       sample.push(arr[i]);

    }
 }

alert(sample.length);

答案 7 :(得分:0)

我将字符串比较和返回唯一项目的操作分开,以使您的代码更易于测试,阅读和重用。

&#13;
&#13;
var unique = function(a){
    return a.length === 0 ? [] : [a[0]].concat(unique(a.filter(function(x){
        return x !== a[0];
    })));
};

var has = function(x){
    return function(y){
        return y.indexOf(x) !== -1;
    };
};

var arr = ["blue-dots", "blue", "red-dots", "orange-dots", "blue-dots"];
var uniquedots = unique(arr.filter(has('dots')));
console.log(uniquedots);
console.log(uniquedots.length);
&#13;
&#13;
&#13;