Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react matching 2 arrays in output

Ok, I am trying to do the following. I have 2 arrays:

item.values:

[0: value: 'ab'],
[1: value: 'cd'],
.....

and array:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

item.choices:

[0: display_value: 'Abort', value: 'ab'],
[1: display_value: 'cds', value: 'cd'],
.....

Now I have the following existing piece of code that I need to modify:

const sortFunc = (a:string, b:string) => {
    const fa = a.toLowerCase(),
        fb = b.toLowerCase();
    if (fa < fb) {
        return -1;
    }
    if (fa > fb) {
        return 1;
    }
    return 0;
}

item.values.sort((a, b) => sortFunc(a.value, b.value)).map((a) => {
    return (<Text key={a.value} children={a.value} />)
});

What I tried is the following:

item.values.sort((a, b) => sortFunc(a.value, b.value)).map((a) => 
    // return (<Text key={a.value} children={a.value} />)
    displayValue(a.value, item.choices)
);

const displayValue = (item: string, item2: any) => {
    if (item2 && item2.length > 0) {
        item2.map((c:any) => {
            if (item !== c.value) {
                return;
            }
            // console.log('yes', item, c.display_value);
            return <Text key={item} children={c.display_value} />
        })
    }
}

The console.log in my piece outputs both items (item and c.display_value) if value from item.values and item.choices match, but the return doesn’t do anything, nothing is shown.

What do I miss?

>Solution :

You are missing a return from the map result:

const displayValue = (item: string, item2: any) => {
    if (item2 && item2.length > 0) {
        return item2.map((c:any) => { // note the added `return`
            if (item !== c.value) {
                return;
            }
            return <Text key={item} children={c.display_value} />
            // This only returns from the callback of the `map`
        })
    }
}

By the way: the resulting array of this mapping may contain undefined values for the cases where the if condition is false. So you probably want to apply .filter(Boolean) to the result first before using it in React to filter out those undefined values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading