I have an array object data called place. When the place array enters the solution function, if the object in the place has a TYPE called 'BOX', I want to extract only the placeId array with 'BOX' TYPE by subtracting the TYPE data of "CONTAINER". Also, if there is no 'BOX' TPYE and only CONTAINER TYPE, I want to extract only the placeId array with "CONAINER" TPYE.
I tried using the map function and filter function in the if statement, but it failed to extract the data and my code doesn't look good either. How do I fix the code?
const place = [
{type: "CONTAINER", placeId: 252 }
]
const place = [
{type: "CONTAINER", placeId: 252 }, {type: "BOX", placeId: 257}, {type: "BOX", placeId: 258}
]
function solution(place) {
if(plaecs.map((v) => v.type === 'BOX')) {
return plaecs.filter((v) => v.type !== 'CONTAINER')
} else if (plaecs.map((v) => v.type !== 'BOX')) {
return plaecs.filter((v) => v.type === "CONTAINER")
}
}
solution(place)
</script>
</body>
</html>
solution(place) expected answer : [252]
solution(place) expected answer : [ 257, 258]
CodePudding user response:
The map
method returns an array. Using if (someArray)
will always go into the body of the if
, because all arrays are truthy (even empty ones).
You're probably looking for the some
method:
if (plaecs.some((v) => v.type === 'BOX')) {
The some
method determines if any element in the array matches the predicate defined by the callback:¹ it calls its callback with the first element of the array and, if the callback returns a truthy value, stops and returns true
; otherwise, it calls the callback with the second element of the array and applies the same logic; etc. If no call to the callback returns a truthy value, some
returns false
(including on an empty array).
¹ So why is it called some
rather than any
? Because it was added in 2009, and some libraries were already adding an any
method to arrays with slightly different semantics, and analysis of existing code in the wild showed that adding any
would break that code. So they went with the second-best name: some
.