0

I have this array containing multiple values of three same strings. But I only want one value from each of the repeated strings and the number of times they are repeated.

For example, from the below array I want the output to be { s: 2, d: 10, p: 4 }

   ["s", "s", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "p", "p", "p", "p"]

I have tried using few loops but I don't know how to get the results I want

Rithish
  • 102
  • 9

6 Answers6

1

Something liks this:

const arr = ["s", "s", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", 
"p", "p", "p", "p"]

const dict = {};
arr.forEach((v) => {
    dict[v] = dict[v] === undefined ? 1 : dict[v]++;
});
Nir Tzezana
  • 2,275
  • 3
  • 33
  • 56
1

This iterates through, checking if the "unique items" object has the character being parsed and increments that property if found, and adds this property to the object if not found (using object.hasOwnProperty).

Output, as expected: { d: 10, p: 4, s: 2 }

var myArr = ["s", "s", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "p", "p", "p", "p"];

const iterator = myArr.values();

var uniqueItems = {};

for (const value of iterator) {
  if (uniqueItems.hasOwnProperty(value)){
    uniqueItems[value] += 1;
  }else{
    uniqueItems[value] = 1;
  }
}
console.log(uniqueItems);
0

You can use reduce & in callback check if accumulator object contains the key. If not create the key and then increment its value by 1

let val = ["s","s",
"d","d","d","d","d","d","d","d","d","d",
"p","p","p","p"].reduce((acc, curr) => {
  acc.hasOwnProperty(curr) || (acc[curr] = 0);
  acc[curr] += 1;
  return acc;
}, {});
console.log(val);
brk
  • 48,835
  • 10
  • 56
  • 78
0

I am using very simple method here. Two loops that check of the same array different values if they are equal and if so count++ and then I return obj[key] = value;

This should work:

function checkRepeated(arr) {
    let repeated = {};
    for(let i=0;i<arr.length;i++) {
        let value = arr[i];
        let count = 0;
        for(let j=0;j<arr.length;j++) {
            if(i != j && value == arr[j]) {
                count++;
            }
        }
        repeated[value] = count+1;
    }
    return repeated;
}
Vichmi
  • 60
  • 5
0

You can have a look of reduce()

const data = [ "s", "s", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "p", "p", "p", "p", ];

const o = data.reduce((a, b) => {
  a[b] ? (a[b] += 1) : (a[b] = 1);
  return a;
}, {});

console.log(o);
ikhvjs
  • 5,316
  • 2
  • 13
  • 36
0

var strigArray = ["s", "s", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "p", "p", "p", "p"];
var reapeat = strigArray.reduce(function(i, n) {
  i[n] = (i[n] || 0) + 1;
  return i;
}, {});

console.log(reapeat);

Please check hope it will work

var strigArray = ["s", "s", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "p", "p", "p", "p"];
var reapeat = strigArray.reduce(function(i, n) {
  i[n] = (i[n] || 0) + 1;
  return i;
}, {});

console.log(reapeat);