最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using join method in nested array - Stack Overflow

programmeradmin0浏览0评论

i have this nested array arr:

[[ "one", "two" , "three"]] I want to extract the values and join them in a var called numbers and separate them by ";"

I used this method :

var itemsArray = arr.join(";");

what i a getting is this :

one,two,three

Although what i am aiming for is one;two;three

It's reading the separator.

i have this nested array arr:

[[ "one", "two" , "three"]] I want to extract the values and join them in a var called numbers and separate them by ";"

I used this method :

var itemsArray = arr.join(";");

what i a getting is this :

one,two,three

Although what i am aiming for is one;two;three

It's reading the separator.

Share Improve this question asked Oct 4, 2016 at 10:27 yasser hyasser h 6292 gold badges10 silver badges18 bronze badges 1
  • 2 Use arr[0].join(';');. The array is nested array. – Tushar Commented Oct 4, 2016 at 10:27
Add a ment  | 

3 Answers 3

Reset to default 4

if the array is nested and number of levels are only two, then try

var arr = [[ "one", "two" , "three"]];
var itemsArray = arr.map( function( item ){ return item.join( ";" )  } ).join(";");

console.log( itemsArray );

You could use a deep joining for nested arrays.

var array = ['zero', ['one', 'two' , 'three', ['four', ['five', 'six', ['seven'], 'eight']]]],
    string = array.map(function join(a) { 
        return Array.isArray(a) ? a.map(join).join(';') : a;
    }).join(";");

console.log(string);

It's a nested array, with the array being in the zeroth index, but you are joining the parent array. Use:

arr[0].join(';');

This takes the first index of the array and joins it.

var arr = [
  ["one", "two", "three"]
];
console.log(arr[0].join(';'));

发布评论

评论列表(0)

  1. 暂无评论