function solution(name, yearning, photo) {
const result = [];
photo.forEach((ele)=>{
result.push(ele.reduce((acc, cur)=>{
const idx = name.indexOf(cur)
return idx >= 0 ? acc += yearning[idx] : acc+=0;
},0))
})
// for(let i = 0; i<photo.length; i++){
// result.push(photo[i].reduce((acc, cur)=>{
// const idx = name.indexOf(cur)
// return idx >= 0 ? acc += yearning[idx] : acc+=0;
// },0))
// }
return result;
}
아직 for문이 더 생각을 정리하기 편해서 먼저 for문으로 작성 후, forEach로 변경 다시 작성했다.
function solution(name, yearning, photo) {
let obj = {};
for(let i = 0; i < name.length; i++){
obj[name[i]] = yearning[i];
}
return photo.map(value => value.map(v => obj[v] ? obj[v] : 0).reduce((acc,cur) => acc + cur,0))
}
이름과 점수를 각각 키와 값으로 객체화 후 풀이. map을 사용해서 새롭게 배열 변수를 만들지 않고 해결하셨다.
function solution(name, yearning, photo) {
return photo.map((v)=> v.reduce((a, c)=> a += yearning[name.indexOf(c)] ?? 0, 0))
}
?? 사용, 식을 좀 더 단축시켰다.