1

I have following json as sample

var employee=[{sex:'M',id:1},{sex:'M',id:3},{sex:'f',id:4},{sex:'f',id:5}]

I want following array

maleIds=[1,3]
femaleIds=[4,5]

 var testFilter=_.filter(employee,function(obj) {
                return obj.sex=='M';
            });

            var testMap=_.map(testFilter, function(value, key){
                return { name : key, value : value };
            });

How can I create array from object using specific criteria ?

_filter / _map they return whole object . I want only sex value .

1 Answer 1

1

First partition the employee data. This will return an array of 2 arrays; the first array contains all the males and the second the females. Then use pluck on the partitioned data to get the ids:

var employee=[{sex:'M',id:1},{sex:'M',id:3},{sex:'f',id:4},{sex:'f',id:5}]

var partitions = _.partition(employee, {sex: 'M'})

var maleIds = _.pluck(partitions[0], 'id');
var femaleIds = _.pluck(partitions[1], 'id');

	var employee=[{sex:'M',id:1},{sex:'M',id:3},{sex:'f',id:4},{sex:'f',id:5}]

	var partitions = _.partition(employee, {sex: 'M'})

	var maleIds = _.pluck(partitions[0], 'id');
	var femaleIds = _.pluck(partitions[1], 'id');

document.getElementById('males').textContent = JSON.stringify(maleIds);
document.getElementById('females').textContent = JSON.stringify(femaleIds);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<p>
  males <pre id="males"></pre>
  females <pre id="females"></pre>
</p>

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

1 Comment

thanks very much . i am very new to underscore , and project time limit didn't let me to study whole documentation .

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.