Returning a single value from a filter

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Returning a single value from a filter



I am trying to return a single value from a filter that returns a large object.


return data.filter(subject => subject.id === 1)
.map((subject) =>
return subject.total.toString();
);



I have tried, toString, JSON.parse and a few more but always get it either as a single array value.



[112]



or a string inside the array



["112"]



but not a single returned value



112



Is map the wrong method? How do I return a pure integer or string would do?





The docs of filter function says that its return type is array developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
– Ionut
Aug 8 at 13:05



filter


array




4 Answers
4



You just need to pick the first element. This should suffice..


return data.filter(subject => subject.id === 1)[0].total+""





Good answer, thanks I prefer "find" though
– leblaireau
Aug 8 at 13:54






find is also more performant, because it stops as soon as it finds a match. Filter will continue and process the whole array anyway.
– Jeremy Thille
Aug 8 at 19:00


find



Instead of filter which returns an array with filtered values, use find:


filter


find


const subject = data.find(subject => subject.id === 1);
return subject.total.toString();



or shorter:


return data.find(subject => subject.id === 1).total.toString();



What about


return data
.filter(subject => subject.id === 1)
.map(subject => subject.total.toString())[0] // Take the first element of the array :)



Array.map returns an array. If your initial array contains one element, the output array will also contain one element. Just extract it with [0].


Array.map


[0]



Alternatively. find() returns one object :


find()


return data.find(subject => subject.id === 1).total.toString()



Filter will always return a array to get the first element use pop


pop


return data.filter(subject => subject.id === 1)
.map((subject) =>
return subject.total;
).pop();






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS