Merge branch 'master' into patch-2
This commit is contained in:
@ -4,5 +4,5 @@ Use Array spread operators (`...`) to concatenate an array with any additional a
|
||||
|
||||
```js
|
||||
const ArrayConcat = (arr, ...args) => [...arr,...args];
|
||||
// ArrayConcat([1], [1, 2, 3, [4]]) -> [1, 2, 3, [4]]
|
||||
// ArrayConcat([1], [1, 2, 3, [4]]) -> [1, 1, 2, 3, [4]]
|
||||
```
|
||||
|
||||
@ -1,9 +1,9 @@
|
||||
### Array without
|
||||
|
||||
Use `Array.filter()` to create an array excluding all given values.
|
||||
Use `Array.filter()` to create an array excluding(using `!Array.includes()`) all given values.
|
||||
|
||||
```js
|
||||
const without = (arr, ...args) => arr.filter(v => args.indexOf(v) === -1);
|
||||
// without[2, 1, 2, 3], 1, 2) -> [3]
|
||||
const without = (arr, ...args) => arr.filter(v => !args.includes(v));
|
||||
// without([2, 1, 2, 3], 1, 2) -> [3]
|
||||
// without([2, 1, 2, 3, 4, 5, 5, 5, 3, 2, 7, 7], 3, 1, 5, 2) -> [ 4, 7, 7 ]
|
||||
```
|
||||
|
||||
@ -5,6 +5,6 @@ You can omit `start` to use a default value of `0`.
|
||||
|
||||
```js
|
||||
const initializeArrayRange = (end, start = 0) =>
|
||||
Array.apply(null, Array(end - start)).map((v, i) => i + start);
|
||||
Array.from({ length: end - start }).map((v, i) => i + start)
|
||||
// initializeArrayRange(5) -> [0,1,2,3,4]
|
||||
```
|
||||
|
||||
19
snippets/read-file-to-array.md
Normal file
19
snippets/read-file-to-array.md
Normal file
@ -0,0 +1,19 @@
|
||||
### Read a file to an Array
|
||||
|
||||
Use `readFileSync` function in `fs` node package to create a `Buffer` from a file.
|
||||
convert buffer to string using `toString(encoding)` function.
|
||||
creating an array from contents of file by `split`ing file content line by line(each `\n`).
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const readFileToArray = filename => fs.readFileSync(filename).toString('UTF8').split('\n');
|
||||
/*
|
||||
contents of test.txt :
|
||||
line1
|
||||
line2
|
||||
line3
|
||||
___________________________
|
||||
let arr = readFileToArray('test.txt')
|
||||
console.log(arr) // -> ['line1', 'line2', 'line3']
|
||||
*/
|
||||
```
|
||||
8
snippets/take-every-nth-element.md
Normal file
8
snippets/take-every-nth-element.md
Normal file
@ -0,0 +1,8 @@
|
||||
### Take every nth element of an array
|
||||
|
||||
Use `Array.filter()` to create a new array that contains every nth element of a given array.
|
||||
|
||||
```js
|
||||
const everynth = (arr, nth) => arr.filter((e, i) => i % nth === 0);
|
||||
// everynth([1,2,3,4,5,6], 2) -> [ 1, 3, 5 ]
|
||||
```
|
||||
@ -1,4 +1,4 @@
|
||||
### Write a JSON to a file
|
||||
### Write JSON to file
|
||||
|
||||
Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user