stargateatlantis
asked on
shouldn't return object in array
If you run the following code below it will return Object as the first item. But Object shouldn't be there.
When you console log this
console.log(foodsMap);
it will return this
Array [ Object, "Salad", "Ricea", "Bue Berries" ]
But why does it return Object in the array. How do I fix that,
When you console log this
console.log(foodsMap);
it will return this
Array [ Object, "Salad", "Ricea", "Bue Berries" ]
But why does it return Object in the array. How do I fix that,
var foods = [
{ name: 'Protien', price: 3 },
{ name: 'Salad', price: 2 },
{ name: 'Ricea', price: 2 },
{ name: 'Bue Berries', price: 2 },
];
var foodsMap = foods.map(function(food){
var foodArray={};
if(food.price==2){
foodArray=food.name;
}
return foodArray;
});
console.log(foodsMap);
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You will need to remove these after you get the result from map(). Updated code below:
However, a better approach would be to write your own filtering function (see below) since map doesn't actually remove the unwanted items.
var foods = [
{ name: 'Protein', price: 3 },
{ name: 'Salad', price: 2 },
{ name: 'Rice', price: 2 },
{ name: 'Bue Berries', price: 2 }
];
// add the index to inspect the element's index
var foodsMap = foods.map(function(food,index){
//console.log(index);
if(food.price==2){
return food.name
}
// if you omit the statement below, you are implicitly
// returning [i]undefined[/i] and it will still occupy a slot in the resulting array.
return undefined;
});
//sort the array. 'undefined' items end up at the end of the array
foodsMap.sort(function(a,b){return a>b ? 1:-1});
//remove undefined items from the end
while(foodsMap[foodsMap.length-1]==undefined){
foodsMap.pop();
}
alert(foodsMap);
However, a better approach would be to write your own filtering function (see below) since map doesn't actually remove the unwanted items.
var foods = [
{ name: 'Protein', price: 3 },
{ name: 'Salad', price: 2 },
{ name: 'Rice', price: 2 },
{ name: 'Bue Berries', price: 2 }
];
function filterData( src ){
var data=[];
for(var i=0; i < src.length; ++i)
{
if( src[i].price==2 )
{
data.push(src[i].name)
}
}
return data;
}
alert( filterData(foods) );
ASKER