1

I have the array ["oop", "poo", "oop", "kkd", "ddd", "kkd"].

Is there any elegant way I can split it to sub-arrays, so each array contains elements with same values?

I want to achieve the following

var arrayOne = ["oop", "oop"]
var arrayTwo = ["poo"]
var arrayThree = ["kkd", "kkd"]
var arrayFour = ["ddd"]
1
  • 1
    Please edit your question and include an example of the desired result. Commented Sep 11, 2017 at 17:54

4 Answers 4

3

You could use reduce.

var arr = ["oop", "poo", "oop", "kkd", "ddd", "kkd"];
var mapped = arr.reduce((map, val)=>{
     if(!map[val]) {
         map[val]=[];
     }
     map[val].push(val); 
     return map;
}, {});

You can even get weird and make it a 1 liner, although probably not the brightest idea just in terms of clarity.

arr.reduce((m, v)=>(m[v]=m[v]||[]).push(v) && m, {});
Sign up to request clarification or add additional context in comments.

Comments

3

You could maybe do something like this, but the requirement kinda feels like a code smell in the first place.

const mixedArray = ["oop", "poo", "oop", "kkd", "ddd", "kkd"];
const splitArrays = {};

mixedArray.forEach(v => {
  if (!!splitArrays[v]) {
    splitArrays[v].push(v);
  } else {
    splitArrays[v] = [v];
  }
})

console.log(splitArrays);

edit: If functional purity is a concern then ug_'s use of reduce is ipso facto preferable.

1 Comment

Also, teehee, "poo".
1

You can create a dictionary counting the values:

counter = {}

L = myArray.length
for (var i = 0; i < L; i++)
{
    if (myArray[i] in counter)
    {
        counter[myArray[i]]+=1
    }
    else
    {
        counter[myArray[i]]=1
    }
}

Comments

1

You could reduce and destructure

var arr = ["oop", "poo", "oop", "kkd", "ddd", "kkd"];
var obj = arr.reduce( (a,b) => (a[b] = a[b] + 1 || 1, a), {});

var [arrayOne, arrayTwo, arrayThree, arrayFour] = Object.keys(obj).map(k=>Array(obj[k]).fill(k));

console.log(arrayOne, arrayTwo, arrayThree, arrayFour);

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.