30

I have an array that consists of objects with two properties.

One property "value" is a number between 1 and 6. The other property "id" is a number between 1 and 200.

How can I return the "id" property of all objects with "value" = 1 and write them to a new array?

3
  • Hi, just wondering where you got stuck? Do you know how to loop over an array? Do you know how to get a property from an object? Do you know how to use an if statement to compare values, and do different things based on that? Do you know how to create a new array, and add things to it? Commented Nov 10, 2014 at 13:02
  • Well, I was just looking for an idea that has the least code. I want to keep my "big/original" array throughout the code and was looking for a way to access the id property easily. Commented Nov 10, 2014 at 13:18
  • No, I didn't mean to ask why you were doing this. Sure, it might be a good idea to extract out an array of IDs and keep it around. I was asking, where did you get stuck in figuring out how to do it. I was just curious, since this involves absolutely basic, fundamental, rudimentary, foundational JS constructs, namely looping over the array to get each object, then getting its property value, then comparing it, then sticking it in an array. What other ideas could there be? And why do you care about "least" code at this point when you haven't written any code at all? Commented Nov 10, 2014 at 13:23

5 Answers 5

52

You should invoke the Array.prototype.filter function there.

var filteredArray = YourArray.filter(function( obj ) {
    return obj.value === 1;
});

.filter() requires you to return the desired condition. It will create a new array, based on the filtered results. If you further want to operate on that filtered Array, you could invoke more methods, like in your instance .map()

var filteredArray = YourArray.filter(function( obj ) {
    return obj.value === 1;
}).map(function( obj ) {
    return obj.id;
});

console.log( filteredArrays ); // a list of ids

... and somewhere in the near future, we can eventually use the Arrow functions of ES6, which makes this code even more beauty:

var filteredArray = YourArray.filter( obj => obj.value === 1 ).map( obj => obj.id );
Sign up to request clarification or add additional context in comments.

3 Comments

Of course this is the right solution, but I'm just wondering about whether it's a good idea to throw functions taking functions, not to mention ES6 arrow functions, at someone who seems to have gotten stuck somewhere between loops, object property references, if statements, and array creation. BTW, you left out the cool array comprehension version. :-)
@torazaburo Well in my mind, its always a good idea to provide convenient and simple solutions.
I posted the comprehension version, as long as we're edging into ES6-land. As for the real-world solution, in this case I sort of like @MichaelFreund's old-school approach (assuming he fixed the for...in loop).
4

Pure JS.... no filter/map functions, that are not available for IE < 9

var array = [
        {id:10, value:2}, {id:11, value:1}, {id:12, value:3}, {id:13, value:1}
    ],
    result = [];
for(key in array) { if (array[key].value == 1) result.push(array[key].id); }

5 Comments

True, but it would also include crap like .length and properly other properties, if you loop over an Array using for..in.
@jAndy: Actually, for...in will not iterate over length. 'length' is not an enumerable property.
@torazaburo as the author explicitly mentioned here, its for browsers like < IE9. Those browsers had no clue about property descriptors.
I don't understand your comment. for...in will not iterate over length in any browser built since the dawn of time. It was always non-enumerable, even way back when when enumerability was strictly a concept internal to engines.
If you definitely want to filter those out, just do this in the loop if (array.hasOwnProperty(key) && array[key].value == 1)
0

You can use a combination of Array.prototype.filter and Array.prototype.map.

First, filter only values with value equal to 1.

arr.filter(function (obj) {
    return obj.value === 1;
});

Then, you map existing collection to a new array, consisting only of id properties stored in filtered array. So the final code:

var newArr = arr.filter(function (obj) {
    return obj.value === 1;
}).map(function (obj) {
    return obj.id;
}); 

Comments

-1

The good news is, it's easy, just write

[ for (obj of array) if (obj.value === 1) obj.id ]

The bad news is, it will some time before you can depend on all browsers to do this. It's from a new version of the language called "ES6". But you can try it right now in Firefox!!

1 Comment

Whoops! Array comprehensions were dropped in ES6 and there seems no plan to include them in the next thing. As it says here (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…): "don't use"! It seems that it works on FF but no other browsers. I'm not clear what constructs could be used instead (other than a not-at-all-sexy plodding loop): map, filter... ?
-1

for multiple items to be searched from an array into some array of objects, use this

let old = []
ao = [{}, {}], array of objects
let newlist = []
old.map(a => ao.find(x => x.Name == a)!==undefined? newlist.push(ao.find(x => x.Name == a)): null)

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.