1

Quick question. I need to create an array using duplicated index. For example, I have an array like:

var array = [2, 3, 2, 4, 3, 2, 6, 7];

And I need to get a new loop interaction for each duplicate index, the response should be something like:

[ 
  [2, 3, 4, 6, 7],
  [2, 3],
  [2],
]

Please let me know if is possible and how to create some function to do it.

Thank you!

5
  • 2
    What is the logic behind the wanted results? Commented Aug 21, 2017 at 19:01
  • @Teemu: As I understand it, it looks like any time you encounter a value, you try putting it into the lowest-indexed output array that doesn't already have that number in it. Commented Aug 21, 2017 at 19:02
  • Wouldn't it be simpler just to count how many of each number there are in the array? Commented Aug 21, 2017 at 19:02
  • Only if the count of each number is the desired output. Commented Aug 21, 2017 at 19:03
  • @Teemu, I need to call an API for each interaction Commented Aug 21, 2017 at 19:05

2 Answers 2

2

You can just use one object to store number of occurrences for each element and use that value to create result array.

var array = [2, 3, 2, 4, 3, 2, 6, 7];
var obj = {}, result = []
array.forEach(function(e) {
  obj[e] == undefined ? obj[e] = 0 : obj[e] += 1;
  result[obj[e]] = (result[obj[e]] || []).concat(e)
})

console.log(JSON.stringify(result))

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

Comments

2

you can do something like this

var array = [2, 3, 2, 4, 3, 2, 6, 7];
array.sort();
let idx = 0, result = [];
for(let i=0; i<array.length; i++){
    if(i>0 && array[i] != array[i-1]){
        idx = 0;
    }
    if(idx == result.length)
        result[idx] = [];
    result[idx].push(array[i]);
    idx++;
}

console.log(result);

1 Comment

Works fine and as expected! Thank you!

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.