Javascript how to show each element of array on a new line
Asked Answered
E

3

30

I have a string build form comma separated values I use split to get each value and after that I want to show each value on a new line but what really happens is that I get each value on a new line except of the last two which are shown together on a same line. Just to make it clear:

value1

,value2

,value3

,value4,value5

Here is the function which I'm using:

_checkDates: function(dates) {
    if (dates != null)
    {
        var zzz = dates.split(',');
        var xxx = zzz.length;
        console.log(xxx);
        for (var i=0; i<=xxx; i++)
        {
            zzz[i] = zzz[i] + '<br />';
            return zzz;
        }
    }
    return dates;
}

Just to be clear this is written in ExtJS 4, I'm almost sure that in this case the problem is pure JavaScript and is not related with ExtJS 4 but anyways, maybe I'm wrong.

So any ideas why does it happen and how I could make that last element to get on a new line as well?

Easiness answered 11/6, 2012 at 15:15 Comment(2)
why in your for loop do have an equal sign. it should be less then. eg. if zzz has length 5 (xxx=5) you want to access elements 0 to 4, value 1 index =0, value2 index =1, value3 index =2, value4 index =3 and value5 index=4. currently you are doing 0 to 5. because the loop exits after you reach 5 not 4. thus you are trying to access zzz[5] which doesn't have any value.Interject
I know that, but i tried with < and <= even with == it didn't work. I don't know the reason why the <br /> tag is not assigned, in fact that is why I post the question. The answer of Stefan below solve my current problem but I would be grateful if someone tell me where is the mistake in my script and how to modify it in order to work properly.Easiness
W
18

The for-loop is suspicious. Firstly, you do not process all items (the last one is missing, as @sarfraz pointed out). Sencondly you are returning the result (zzz) in the for-loop body:

for (var i=0; i<=xxx; i++)
{
  zzz[i] = zzz[i] + '<br />';
  return zzz; // for-loop will stop here! resulting in ["value1<br />", "Value2", etc...]
}

In Javscript you can simple "join" the array:

return dates.split(',').join("<br />")

Since you are simply replacing strings you could use the replace method:

return dates.replace(",", "<br />");
Watford answered 11/6, 2012 at 15:21 Comment(1)
return dates.split(',').join("<br />") - exactly what I need. Thanks.Easiness
M
47

i have modified your function bit cleaner.since already stefan mentioned your mistake.

function splitDate(dates) {
    if (dates != null)
    {
        var dates = dates.split(',');
        var xxx = dates.length;
        console.log(xxx);
        for (var i=0; i<xxx; i++)
        {
            dates[i] = dates[i];                    
        }
    }
    console.log(dates.join('\r\n'));
    return dates.join('\r\n');        
}

the above function you can do it in a single line:

if it's an array you can split into new line in following way:

var arr = ['apple','banana','mango'];
console.log(arr.join('\r\n'));

if it's a string:

var str = "apple,banana,mango";
console.log(str.split(',').join("\r\n"));
Manageable answered 21/11, 2015 at 10:14 Comment(2)
you can do console.log(arr.join('<br>'));Pithos
arrayVar.forEach(_ => console.log(_)) in case you can try this too in loopingMonitorial
W
18

The for-loop is suspicious. Firstly, you do not process all items (the last one is missing, as @sarfraz pointed out). Sencondly you are returning the result (zzz) in the for-loop body:

for (var i=0; i<=xxx; i++)
{
  zzz[i] = zzz[i] + '<br />';
  return zzz; // for-loop will stop here! resulting in ["value1<br />", "Value2", etc...]
}

In Javscript you can simple "join" the array:

return dates.split(',').join("<br />")

Since you are simply replacing strings you could use the replace method:

return dates.replace(",", "<br />");
Watford answered 11/6, 2012 at 15:21 Comment(1)
return dates.split(',').join("<br />") - exactly what I need. Thanks.Easiness
M
3

Link: https://snack.expo.io/GcMeWpPUX

import React from 'react'
import { SafeAreaView, Text, View, FlatList } from 'react-native'

export default class App extends React.Component {

    render() {
        return (
            <SafeAreaView style={{ flex: 1, alignItems: 'center', justifyContent: 'center',margin:20 }}>
                <FlatList
                    data={your_array_name}
                    keyExtractor={(item, index) => String(index)}
                    renderItem={({ item, index }) => {
                        return (
                            <Text style={{ color: '#ff8500', fontSize: 18 }}>{item.skills.splice(',').join("\n")}</Text>
                        )
                    }}
                />

            </SafeAreaView>
        )
    }

}


const your_array_name = [
    {
        id: 1,
        text: 'Lorem ipsum is simple dummy text for printing the line',
        skills: ['javascript', 'java']
    },
    {
        id: 2,
        text: 'Lorem ipsum is simple dummy text.',
        skills: ['javascript', 'java']
    }]
Mcilwain answered 19/8, 2019 at 10:41 Comment(3)
thanks @Hardik Desai your solution helped me to fix the issue while rendering the arrayEiger
@vaibhavnaik Welcome ✌️ ;)Mcilwain
Thank you, that was a great help. .splice(',').join("\n"), worked in a simple way for me.Besmear

© 2022 - 2024 — McMap. All rights reserved.