sal sal - 22 days ago 9
Javascript Question

Javascript MarkActive Function

I am trying to implement a function "markActive", which, when given a list of objects and an id, returns the same list, but with the corresponding object marked active, like for example,

var list = [
{ id: 1, active: false },
{ id: 2, active: false },
{ id: 3, active: true },
{ id: 4, active: false }
];


when function is called

markActive(list, 2);


should Return:

[
{ id: 1, active: false },
{ id: 2, active: true },
{ id: 3, active: false },
{ id: 4, active: false }
]


i tried many loops but everytime i was getting undefined,
thank you in advance.

Answer

You could iterate the array and set active with a check of the id.

function markActive(array, id) {
    array.forEach(function (o) {
        o.active = o.id === id;
    });
    return list;
}

var list = [{ id: 1, active: false }, { id: 2, active: false }, { id: 3, active: true }, { id: 4, active: false }];

console.log(markActive(list, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments