2

I need to split an array into several sub arrays and replace a certain character.

First I run a function to count the number of duplicates in the array. Then I build a new array with the values and the number of instances of the value.

Code:

    angular.forEach($scope.financial, function(data) {
        counts[data] = (counts[data] || 0)+1; 
    })

Result:

[4, {25: 4}, 5, {25: 1}, 3, {10: 1}, 4, {10: 1}]

What I am looking for is to split the array into several sub arrays and replace the colon with a comma.

Like this:

[[4,25,4],[5,25,1],[3,10,1],[4,10,1]]

Any suggestions?

3
  • 3
    Can you show us the initial contents of $scope.financial? Commented Sep 28, 2015 at 12:22
  • The initial content is like this: [[4,25],[5,25],[3,10],[4,10]] Commented Sep 28, 2015 at 12:28
  • Why not use regular objects with property names instead? Sure beats having to read documentation to know what different indices mean... Commented Sep 28, 2015 at 12:30

2 Answers 2

1

That can be done with a simple loop. But, some checks for the integrity of the data would be advised if you can't guarantee the format of the input.

function getKey(o) {
  for (var prop in o) {
    if (o.hasOwnProperty(prop)) {
      return prop;
    }
  }
}

var data = [4, {25: 4}, 5, {25: 1}, 3, {10: 1}, 4, {10: 1}];
var i = 0;
var output = [];
var key;

for (i = 0; i < data.length; i += 2) {
  key = getKey(data[i + 1]);
  output.push([data[i], parseInt(key, 10), data[i + 1][key]]);
}

//Print the output
console.log(output);

var el = document.createElement('div');
el.innerHTML = JSON.stringify(output);
document.body.appendChild(el);

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

Comments

1

The below mentioned converter function will accept the reponseArray of type [4, {25: 4}, 5, {25: 1}, 3, {10: 1}, 4, {10: 1}] and converts into subarray [[4,25,4],[5,25,1],[3,10,1],[4,10,1]]

fiddle

function converter(responseArray) {
    var mainArray=[], subArray;
    for (var i = 0; i < responseArray.length; i++) { 
        if(i%2 == 0) {
         subArray= [];
         subArray.push(responseArray[i]);
        } else {
             var obj = responseArray[i];
             for(var key in obj) {
                subArray.push(key * 1);
                subArray.push(obj[key] * 1);
             }
             mainArray.push(subArray);
        }
    }
    console.log(mainArray);
    return mainArray;
}

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.