I'm facing an issue with a function that filters an array.
My goal is to retrieve only the string value, not the entire object.
However, I keep getting back the entire object instead of just the string.
Interestingly, when I switch the return statement to console.log(), I get the desired output.
Any suggestions on why this might be happening?
Below is the code snippet:
const Array2 = [
{ header: 'First name', HeaderIndex: 0},
{ header: 'Last name', HeaderIndex: 1},
{ header: 'Company', HeaderIndex: 2},
{ header: 'Favorite food', HeaderIndex: 3},
{ header: 'Favorite color', HeaderIndex: 4},
]
const testing = Array2.filter((obj) => { if(obj.HeaderIndex === 1) { return obj.header } } )
console.log(testing)
// receiving undesired output
[{…}]
0: {header: 'Last name', HeaderIndex: 1}
length: 1
[[Prototype]]: Array(0)
const testing = Array2.filter((obj) => { if(obj.HeaderIndex === 1) { console.log(obj.header)} } )
// obtaining desired output
"Last name"
The problematic output is displayed below; my intention is to only return the string value.
[{…}]
0: {header: 'Last name', HeaderIndex: 1}
length: 1
[[Prototype]]: Array(0)
Update*
I accepted the solution from Mayur as it resolved my problem in a larger use case. Below is the expanded scenario where I needed to combine these two arrays based on matching Array1 index with HeaderIndex from Array2.
const Array1 = [
['Alex', 'Boe', 'MeowWolf', 'pizza', 'pink'],
['Arron', 'Coe', 'Kmart', 'tofu', 'purple'],
['Jane', 'Doe', 'Sears', 'tacos', 'orange'],
['John', 'Eoe', 'YugiOh', 'blueberries', 'magenta'],
['Suzie', 'Boe', 'Toyota', 'steroids', 'blue']
]
const Array2 = [
{ header: 'First name', HeaderIndex: 0},
{ header: 'Last name', HeaderIndex: 1},
{ header: 'Company', HeaderIndex: 2},
{ header: 'Favorite food', HeaderIndex: 3},
{ header: 'Favorite color', HeaderIndex: 4},
]
const testResult = Array1.map((arr) => arr.map((string) => { return {"ChosenHeader": Array2.filter((obj) => obj.HeaderIndex === arr.indexOf(string))[0]?.header, "content": string}} ))
console.log(testResult)
// expected output
[
0: {ChosenHeader: 'First name', content: 'Alex'}
1: {ChosenHeader: 'Last name', content: 'Boe'}
2: {ChosenHeader: 'Company', content: 'MeowWolf'}
3: {ChosenHeader: 'Favorite food', content: 'pizza'}
4: {ChosenHeader: 'Favorite color', content: 'pink'}
]