Home > OS >  How to export values that are repeated X amount of time from array in JavaScript?
How to export values that are repeated X amount of time from array in JavaScript?

Time:09-11

Lets say I have an array of numbers

let answerKey = ['0', '0', '1', '2', '2']

I want to test the number of repeats (number of instances) of each value

If the number of instances meets the requirement, then push that value to another array

let processKey = []

If the requirement = 2, and there are 2 instances of '0', processedKey.push(0)

What are some ways to tackle this?

I'ved tried

for(let prop in answerKey){
        let counter = 0
        answerKey.forEach(element => {
            if (element === element) {
              counter  ;
            }
          });
        if (counter == length){
            processedKey.push(prop)
        }
    }

CodePudding user response:

It is so simple:

let repeated=2;
let answerKey = ['0', '0', '1', '2', '2']

function findRepeated(arr,n){
  // validation checking
  if (!Array.isArray(answerKey) || answerKey.length === 0){
    return {}
  }
  // convert the array to an object (dictionary) and give all values zeros
  let myDic = answerKey.reduce(function(acc, cur, i) {
    acc[cur] = 0;
    return acc;
  }, {})
  // loop through the array and assign them their values
  for (let i=0;i<answerKey.length;i =1){
    myDic[arr[i]] = myDic[arr[i]] 1;
  }
  // returning the object
  return Object.keys(myDic)
    .filter(i=>myDic[i]===repeated)
}

// calling the function
let processedKeys = findRepeated(answerKey, repeated);
console.log(processedKeys)

CodePudding user response:

Here's how I see it.

  1. Step - count, how many times each value is presented in the original array
  2. Filter the values where repeats count exactly equals to the expected value

const repeatKey = 2;
let answerKey = ['0', '0', '1', '2', '2'];
const repeats = answerKey.reduce((collector, value) => { 
  collector[value] = (collector[value] | 0)   1; 
  return collector; 
}, {});

const processedKey= Object.keys(repeats).filter(key => repeats[key] === repeatKey);
console.log(processedKey);

  • Related