2

I have an array of strings:

var array = ['bob', 'charlie', 'bob', 'bob']; 

that I want to remove duplicates from, and then I'd like to convert it to an array of objects whilst adding a duplicate count property.

This is what I want to achieve:

var filteredData = [{ name: 'bob', count: 3}, { name: 'charlie', count: 1}];

How can I do that?

2

3 Answers 3

3

Ecmascript5 solution using Array.prototype.reduce() function:

var arr = ['bob', 'charlie', 'bob', 'bob'],
    counts = arr.reduce(function(r,s){
        (!r[s])? r[s] = {name: s, count: 1} : r[s]['count']+=1;
        return r;
    }, {}),
    result = Object.keys(counts).map(function(k){ return counts[k]; });
    
console.log(result);


Ecmascript6 version (with Object.values() function):

var arr = ['bob', 'charlie', 'bob', 'bob'],
    result = Object.values(arr.reduce((r,s) => {
        (!r[s])? r[s] = {name: s, count: 1} : r[s]['count']+=1;
        return r;
    }, {}));
    
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

Using Map with Array#reduce:

const array = ['bob', 'charlie', 'bob', 'bob']; 

const result = [...array.reduce((map, name) => {
  const current = map.get(name) || { name, count: 0 };
  
  current.count++;

  return map.set(name, current);
}, new Map()).values()];

console.log(result);

Comments

0

Here is some straightforward usage of Array.prototype.reduce:

const data = ['bob', 'charlie', 'bob', 'bob']

const result = data.reduce(function(prev, curr) {
  const index = prev.findIndex(el => el.name === curr)

  if (index !== -1) {
    prev[index].count += 1
  } else {
    prev.push({ name: curr, count: 1 })
  }

  return prev
}, [])

console.log(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.