提供数组中值出现的泛型函数

时间:2019-02-26 09:42:16

标签: javascript arrays

必须用所有至少发生一次的项目构建第一个数组,用至少两次出现的项目构建第二个数组,以此类推。

 var arr1 = ["Hi", "Hey", "Hello", "ABC", "Hi", "Hi", "Hello","ABC", "Hello"];

 Expected output format:
 run1 = ["Hi", "Hey", "Hello", "ABC"] //Here first array with all items that occur at least once
 run2 = ["Hi", "Hello","ABC"]// Items occur twice
 run3 = ["Hi", "Hello"] // Items occur thrice 

必须设计通用功能来处理这种情况。

5 个答案:

答案 0 :(得分:1)

检查以下代码...

var arr1 = ["Hi", "Hey", "Hello", "ABC", "Hi", "Hi", "Hello","ABC", "Hello"];

function findOccured(array, count)
{
        result = [];
        arr1.forEach(element => {
         if(arr1.filter(item => item == element).length >= count){result.push(element);}
        });
        return result;
}

run1 = Array.from(new Set(arr1));
run2 = Array.from(new Set(findOccured(arr1, 2)));
run3 = Array.from(new Set(findOccured(arr1, 3)));
console.log(run1);
console.log(run2);
console.log(run3);

Output as expected :

答案 1 :(得分:0)

使用Map和Array#reduce,您可以执行以下操作。

地图->跟踪元素计数

const data = ["Hi", "Hey", "Hello", "ABC", "Hi", "Hi", "Hello","ABC", "Hello"];
 
 const res = data.reduce(({counter,res},c)=>{

    counter.set(c, (counter.get(c)||0) + 1)
    const index = counter.get(c) - 1;

    if(!res[index]) res[index] = [];
    res[index].push(c);

    return {counter, res};
 }, {counter: new Map(), res: []}).res;
 
 console.log(res);

答案 2 :(得分:0)

您可以计算原始数组中每个项目的出现次数,然后根据出现次数来过滤结果。

var arr1 = ["Hi", "Hey", "Hello", "ABC", "Hi", "Hi", "Hello","ABC", "Hello"];
var run1 = [], run2 = [], run3 = []
var count = {};
arr1.forEach((x) => { 
   count[x] = ( count[x] || 0) + 1;
   if (count[x] > 0 && run1.indexOf(x) < 0) run1.push(x)
   if (count[x] > 1 && run2.indexOf(x) < 0) run2.push(x)
   if (count[x] > 2 && run3.indexOf(x) < 0) run3.push(x)
});
console.log(run1);
console.log(run2);
console.log(run3);

答案 3 :(得分:0)

我使用closure来构建动态函数。然后,我们可以保存该迭代,以备下次使用。

var arr1 = ["Hi", "Hey", "Hello", "ABC", "Hi", "Hi", "Hello","ABC", "Hello"];

function buildSet() {
  const rsObj = arr1.reduce((acc, item) => {
   acc[item] = acc[item] || 0
   acc[item]++ 
   return acc
  }, {})
  
  return function(time) {
    return Object.entries(rsObj).reduce((acc, [name, count]) => {
      return count >= time ? acc.concat(name) : acc
    }, [])  
  }
}

const wordLeast = buildSet()

console.log(wordLeast(1))
console.log(wordLeast(2))
console.log(wordLeast(3))

答案 4 :(得分:0)

您可以尝试这些组合

var arr1 = ["Hi", "Hey", "Hello", "ABC", "Hi", "Hi", "Hello", "ABC", "Hello"];

function custom(arr1, cnt) {
  var groups = arr1.reduce(function(acc, e) {
    acc[e] = (e in acc ? acc[e] + 1 : 1);
    return acc
  }, {});
  return Object.keys(groups).filter(function(key) {
    return groups[key] >= cnt
  });
}
var once = custom(arr1, 1);
var twice = custom(arr1, 2);
var thrice = custom(arr1, 3);
console.log(once, twice, thrice);