I wrote a function to find an element inside the array. Because the types of arrays are different(ex:Array1,Array1,Array1,Array1)
, I had a problem with part arr.map(el => el "." n)
, and for my arrays this part must be defined in this way for the function to work.
Array1 =>arr.map(el => el.fullName)
Array2 =>arr.map(el => el.Name)
Array3 =>arr.map(el => el.sName)
Array3 =>arr.map(el => el.sameName)
Friends, can you help me how to solve the problem?
function findNameInArray(arr, name, n) {
let names = arr.map(el => el "." n);
let num = names.indexOf(name);
let ch = arr[num];
return ch
}
Array1 =[{fullName:"name1",snumber:1},{fullName:"name2",snumber:2}];
Array2 =[{Name:"name1",number:1},{Name:"name2",number:2}];
Array3 =[{sName:"name1",snumber:1},{sName:"name2",snumber:2}];
Array4 =[{sameName:"name1",number:1},{sameName:"name2",number:2}];
CodePudding user response:
Based on the code in the question it looks like you really just checking to see if the name exists in the array of objects. You don't need to return the name from the function because you already know what it is.
You can create a function that passes in the array, the name, and the object property that needs to be evalauted, and then use some
to make that evaluation. The function will return a boolean (either true or false).
function nameExists(arr, name, prop) {
return arr.some(obj => obj[prop] === name);
}
const arr = [{fullName:'name1',snumber:1},{fullName:'name2',snumber:2}];
const arr2 = [{sName:'name1',snumber:1},{sName:'name3',snumber:2}];
const arr3 = [{sameName:"name1",number:1},{sameName:"name2",number:2}];
const arr4 = [{sameName:"name1",number:1},{sameName:"Bob",number:2}];
console.log(nameExists(arr, 'name2', 'fullName'));
console.log(nameExists(arr2, 'Bob', 'sName'));
console.log(nameExists(arr3, 'name2', 'sameName'));
console.log(nameExists(arr4, 'Bob', 'job'));