const selectedArr = arr.filter((e,i) => {
if(obj[e]){
return obj[e]
}
})
return selectedArr.map((e,i) => {
return obj[e]
})
const keys = Object.keys(obj)
arr.forEach((element) => {
if (keys.includes(element)) {
result.push(obj[element])
}
})
return result
keys.includes(element)
-> we didn't learn this, and we don't need it, and its slow. Just use the basic object knowledge, why make it so complicated?:
if (keys[element])
const solution = (num, ind = 0, arr = []) => {
if (num === ind) {
return arr;
}
arr.push(ind);
return solution(num, ind + 1, arr);
};
forEach
is not descriptive enough, so your code is not as clear as it could be. You want to use reduce
.
Solution1
const solution = (arr) => {
return (obj) => {
const keys = Object.keys(obj)
return arr.reduce((acc, x) => {
if (keys.includes(x)) {
acc[x] = obj[x]
}
return acc
}, {})
}
}
return (obj, result={}) => {
arr.forEach((e) => {
if (obj[e] === undefined) return
result[e] = obj[e]
})
return result
}