Reduce() method Arrays

reduce(0) method Java script arrays.
let shapes=[
    {
        name:"rectangle",
        dimensions:[2,8,2,8],
        angle:90
    },
    {
        name:"square",
        dimensions:[4,4,4,4],
        angle:90
    },
    {   name:"triangle",
        dimensions:[6,6,6],
        angle:60   
    },
    {
        name:"circle",
        dimensions:[2],
        angle:360
    },
    {
        name:"rhombus",
        dimensions:[6,5,5,5],
        angle:90
    }
]
function perimeter(shp){
    shp.dimensions.reduce((acc,a)=>{
    return acc + a

},0)}

let pm=(perimeter(shapes[0]))
console.log(pm)//undefined
//Please help me with this code why am i getting undefined?

I got the problem but it’s a good catch.Guys please do try out.

Your function doesn’t return anything. It receives an array, does something with that, and… nothing :slight_smile:

const shapes=[
    {
        name: "rectangle",
        dimensions: [ 2, 8, 2, 8 ],
        angle: 90
    },
    {
        name: "square",
        dimensions: [ 4, 4, 4, 4 ],
        angle: 90
    },
    {
        name: "triangle",
        dimensions: [ 6, 6, 6 ],
        angle: 60
    },
    {
        name: "circle",
        dimensions: [ 2 ],
        angle: 360
    },
    {
        name: "rhombus",
        dimensions: [ 6, 5, 5, 5 ],
        angle: 90
    }
]

function perimeter (shp) {
    return shp.dimensions.reduce( (acc, cur) => acc + cur, 0)
}

const pm = perimeter(shapes[0])
console.log(pm)

More importantly… know that all functions return undefined if no return is explicitly stated. So whenever you see that happen,. it’s a huge clue as to what the problem is.

BTW,.

It would make more sense to have a function that did:
perimeter({name: 'rectangle'});

than to do:
perimeter(shapes[0]);