0
var arr = ['cat','cat','dog','penguin','chicken','chicken']

function orgAnimals(input)
   var obj = {};
   for (var i = 0 ; i < input.length; i++) {
      obj[input[i]] = obj[input[i]] || 0;
      obj[input[i]]++
   }
return obj;
}

So this gives me {cat:2, dog:1, penguin:1, chicken:2,}

I want to split the object up into 2 different objects and put it in an array so it looks like

[{cat:2, dog:1} {penguin:1, chicken:2 }]

I tried an if statement to make that work but it's not. if (input[i]==='cat'||'dog') still gives me the same output as before.

Any hints? Am I using the operator incorrectly?

1
  • 1
    if (input[i]==='cat'||'dog') will always be true. Commented Oct 10, 2016 at 18:24

2 Answers 2

2

Golf time, I suppose

var arr = ['cat','cat','dog','penguin','chicken','chicken']

function orgAnimals(input) {
    return input.reduce((a, b) => {
    	var i = ['cat','dog'].indexOf(b) === -1 ? 1 : 0;
      	return b in a[i] ? a[i][b]++ : a[i][b] = 1, a
    }, [{},{}]);
}

console.log( orgAnimals(arr) );

Same logic, but a little more readable, where you check if the iterated value is either cat or dog and insert into the array based on a condition

var arr = ['cat', 'cat', 'dog', 'penguin', 'chicken', 'chicken']

function orgAnimals(input) {
    var arr = [{}, {}];
    
    for (var i = 0; i < input.length; i++) {
    
        if ( input[i] === 'dog' || input[i] === 'cat') {
        	if ( input[i] in arr[0] ) {
            	arr[0][ input[i] ] = arr[0][ input[i] ] + 1;
            } else {
            	arr[0][ input[i] ] = 1;
            }
        } else {
        	if ( input[i] in arr[1] ) {
            	arr[1][ input[i] ] = arr[1][ input[i] ] + 1;
            } else {
            	arr[1][ input[i] ] = 1;
            }
        }
    }
    return arr;
}

console.log( orgAnimals(arr) )

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

Comments

0

You would want to create 2 separate objects and then combine them in your return statement. So something like this:

if ((input[i] == 'cat') || (input[i] == 'dog'))){
  obj1[input[i]] = obj1[input[i]] || 0;
  obj1[input[i]]++
}
else if ((input[i] == 'penguin') || (input[i] == 'chicken')){
  obj2[input[i]] = obj2[input[i]] || 0;
  obj2[input[i]]++
}
return {obj1, obj2}

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.