I’m a beginner-level student and for practice in understanding .map()
, I’m trying to write a callback function that returns an updated list of full names that would return Jim’s last name as Smith etc. employees[0].familyName = lastNames[0]
, employees[1].familyName = lastNames[1]
and so on….
const lastNames = ["Smith", "Anderson"];
const employees = [
{
name: "Jim",
familyName:"",
},
{
name: "Jill",
familyName: "",
}
];
This is what I’ve tried expecting it to return a new object array called fullNames
with the following key/value pairs but am lost in the wrong direction possibly with matching the index numbers:
function lastNameUpdater(arr, objArr) {
let matchNumber = arr.findIndex() === objArr.findIndex();
const fullNames = objArr.map((element) => {
return matchNumber;
if (matchNumber) {
return objArr.key = arr;
}
return fullNames;
})
}
lastNameUpdater(lastNames, employees);
3
Answers
You can use the index argument given to the
map
callback to access the corresponding last name from the other array.You are misusing findIndex; actually, you don’t even need it. You can read more about it here
What you really need is to use the map’s second argument, which is the
index
of the current element in the array, and pick the element under the same index in thelastNames
array.Just use the second
index
parameter that’s passed to the callback, then you can use spread notation to overwrite thefamilyName
attribute. Because the indices match up, this will pair each family name with the correct employee: