Rename js snippets

This commit is contained in:
Angelos Chalaris
2023-05-19 20:23:47 +03:00
parent 82a614e42e
commit 9d032ce05e
305 changed files with 70 additions and 70 deletions

View File

@ -0,0 +1,34 @@
---
title: Join array into string
type: snippet
language: javascript
tags: [array]
cover: couch-laptop
dateModified: 2020-10-22T20:23:47+03:00
---
Joins all elements of an array into a string and returns this string.
Uses a separator and an end separator.
- Use `Array.prototype.reduce()` to combine elements into a string.
- Omit the second argument, `separator`, to use a default separator of `','`.
- Omit the third argument, `end`, to use the same value as `separator` by default.
```js
const join = (arr, separator = ',', end = separator) =>
arr.reduce(
(acc, val, i) =>
i === arr.length - 2
? acc + val + end
: i === arr.length - 1
? acc + val
: acc + val + separator,
''
);
```
```js
join(['pen', 'pineapple', 'apple', 'pen'],',','&'); // 'pen,pineapple,apple&pen'
join(['pen', 'pineapple', 'apple', 'pen'], ','); // 'pen,pineapple,apple,pen'
join(['pen', 'pineapple', 'apple', 'pen']); // 'pen,pineapple,apple,pen'
```