1

I have this array:

[10: "AAA", 30: "BBB", 50: "CCC", 60: "DDD", 80: "EEE", 81: "FFF", 82: "GGG", 83: "HHH"]

and after using command :

myarray.join(' | ')

it will return multiple duplicated pipes. function join means that there is array with indexes 0-10, 11-29, etc. like : [empty × 10, "AAA", empty × 19, "BBB", empty × 19, "CCC", empty × 9, "DDD", empty × 19, "EEE", "FFF", "GGG", "HHH"]

Result is:

| | | | | | | | | | AAA | | | | | | | | | | | | | | | | | | | | BBB | | | | | | | | | | | | | | | | | | | | CCC | | | | | | | | | | DDD | | | | | | | | | | | | | | | | | | | | EEE | FFF | GGG | HHH

but expected result is:

AAA | BBB | CCC | DDD | EEE | FFF | GGG | HHH

How to join custom indexed array?

step
  • 2,254
  • 2
  • 23
  • 45
  • Filter the array before joining ..? – Teemu Jun 12 '18 at 12:25
  • 1
    You get that result, because that's how the array actually looks like. The array has 83 entries, most of them are `undefined`, but the length of the array is 83. So you probably should think over using a Object or a Set instead of an Array. – t.niese Jun 12 '18 at 12:31
  • this helped to me: myarray= myarray.filter(function(val){return val}); – step Jun 12 '18 at 12:40

3 Answers3

2

filter the blank or undefined entries and then join as normal.

myarray = [];
myarray[10] = 'AAA'; myarray[30] = 'BBB'    
result = myarray.filter(x => x != '' && x != undefined).join('|')
console.log(result)

Edit: For this particular case, filter can be simplified with:

result = myarray.filter(x => x).join('|')
kiddorails
  • 12,961
  • 2
  • 32
  • 41
1

You could filter a sparse array with a callback which returns true and join the result.

var array = [],
    result;

array[10] = "AAA";
array[30] = "BBB";
array[50] = "CCC";
array[60] = "DDD";
array[80] = "EEE";
array[81] = "FFF";
array[82] = "GGG";
array[83] = "HHH";
result = array.filter(_ => true).join('|');
    
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Use Array.filter

let arr = [];
arr[10] = "AAA", arr[30] = "BBB", arr[50] = "CCC", arr[60] = "DDD", arr[80] = "EEE", arr[81] = "FFF", arr[82] = "GGG", arr[83] = "HHH";

let result = arr.filter(v => !!v).join('|');
console.log(result);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59