简体   繁体   English

在数组中查找偶数出现的单词-Javascript

[英]Find the Words with an even number of occurrences in an Array - Javascript

Given an array of words, write a function that returns an array of the words that occur an even number of times. 给定一个单词数组,编写一个函数以返回出现偶数次的单词数组。

function even(["hello", "hi", "hello", "elephant", "hi"]);

That output should be: 该输出应为:

["hello", "hi"]

This has been a toy problem I have been struggling with recently. 这是我最近一直在努力解决的玩具问题。 I have solved similar problems counting and returning the number of occurrences of elements in an array but am having trouble taking that logic and applying it to this problem. 我已经解决了类似的问题:计算并返回数组中元素的出现次数,但是在采用该逻辑并将其应用于该问题时遇到了麻烦。

This is what I have tried so far, but have hit a wall when trying to output just the even occurrences: 到目前为止,这是我尝试过的方法,但是在尝试仅输出偶数事件时遇到了麻烦:

function even(collection) {
  var results = [];
  for(var i = 0; i < collection.length; i++){
    var value = collection[i];
    if(results[value]){
      results[value] = results[value] + 1;
  }else{
   results[value] = 1; 
  }
}
        return results;
}

You can use reduce to get an actual count of the words, then simply return an array of the ones that have an even count: 您可以使用reduce来获得单词的实际计数,然后简单地返回一个具有偶数的单词数组:

function even(wordsArr) {
    //Object of words and counts
    var wordCounts = wordsArr.reduce(function(counts, word) {
        if (!counts.hasOwnProperty(word)) {
            counts[word] = 0;
        }

        counts[word]++;
        return counts;
    }, {});

    //Now filter that out and return
    return Object.keys(wordCounts).filter(function(word) {
        return wordCounts[word] % 2 === 0
    });
}

even(["hello", "hi", "hello", "elephant", "hi"]); //["hello", "hi"]

 var arr = ["hello", "hi", "hello", "elephant", "hi"]; function onlyEvens( arr ) { var countObj = {}; for( var i = 0; i < arr.length; i++ ) { var item = arr[i]; if( countObj[ item ] !== undefined ) countObj[item]++; else countObj[item] = 1; }//for() var filteredArray = []; for(var key in countObj ) { if( countObj[key] % 2 == 0 ) filteredArray.push( key ); } return filteredArray; }//onlyEvens() console.log( onlyEvens( arr ) ); 

Issues in your code: 您的代码中的问题:

  • you use collection instead of words 您使用collection而不是words
  • you cannot access array the associative way. 您不能以关联方式访问数组。 You must declare it as object: 您必须将其声明为对象:

    results[value]

  • you return result variable, but it is undeclared. 您返回result变量,但未声明。

    return result;

  • results only contains the occurrences of every word. 结果仅包含每个单词的出现。 There miss the code that calculates if the occurrences of a word are odd or even. 错过了计算单词出现是奇数还是偶数的代码。

fixed code: 固定代码:

function even(words) {       // <<< in your code was collection
  var results = {};
  for(var i = 0; i < words.length; i++){
    var value = words[i];
    if(results[value]){
      results[value] = results[value] + 1;
    }else{
      results[value] = 1; 
    }
  }
  var ret = [];
  for(var word in results)
    if(results[word]%2 !== 0)
      rest.push(word);

  return ret;
}

 function even(list) { var d = list.reduce(function(d, w) { d[w] = !d[w]; return d; }, {}); return Object.keys(d).filter(function(w) { return !d[w]; }); } console.log(even(["hello", "hi", "hello", "elephant", "hi"])); console.log(even(["hello", "yo", "yo", "hi", "hello", "yo", "elephant", "hi"])); 

Explanation: Use the array .reduce() method to create an object ( d ) with a property for each word ( w ) with a boolean value indicating whether the word has an odd number of occurrences. 说明:使用数组.reduce()方法创建一个对象( d ),该对象( d )具有每个单词( w )的属性,该布尔值表示该单词是否出现奇数个值。 Then .filter() the keys to get all the ones that are not odd. 然后.filter() 获取所有奇数的键。

If you previously sort the array you can filter it as required in just a code line like this : 如果您以前对数组进行了排序,则可以仅在如下代码行中根据需要对其进行过滤:

var even = (str) => str.sort().filter((element, index, arr) => index+1 === arr.lastIndexOf(element));

console.log(even(["hello", "hello", "hi", "elephant", "hi", "hi"])); //[ 'hello', 'hi' ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM