DEV Community

Dahye Ji
Dahye Ji

Posted on

JavaScript Basic - reduce(), sort() and other methods, JSON...

repeat()

repeat() is a method that constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

let str = 'abcde';
str.repeat()  // if it's empty it returns empty string
// ''
str.repeat(2);
// 'abcdeabcde'

let str2 = 'world ';
console.log(`hello : ${str3.repeat(3)}`);
// hello : World World World 
Enter fullscreen mode Exit fullscreen mode

Array.from()

Array.from() is static method creates a new, shallow-copied Array instance from an array-like or iterable object.

Array.from('a', repeat(10));
// ['a','a','a','a','a','a','a','a','a','a']
Array.from(str.repeat(10));
// ['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']
Array.from('abc');
// ['a', 'b', 'c']
Array(10) // this doesn't take any memory because it's empty
// [empty x 10] // they are empty arrays
let emptyArray = Array(10);
emptyArray[5]
// undefined
emptyArray[3] = undefined;
// undefined
emptyArray;
// [empty x 3,, undefined, empty x 6]
Enter fullscreen mode Exit fullscreen mode

fill()

fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

// it was 0 but gave value 10 using map
Array(100).fill(0).map((value) => 10);

// this console.log 100 of undefined in array
Array(100).fill(0).map((value) => console.log(value));

// this takes lots of memory
Arr(100).fill(0).map((value,index,arr) => arr);

// increase by 1 
Array(100).fill(0).map((value, index) => index+1);

// increase by **2 (from 0)
// default value of fill() is zero so if () is empty it 's the same is fill(0)
Array(100).fill().map((value, index) => (index*1)**2);

// increase by **2 (from 1)
Array(100).fill().map((value, index) => (index+1)**2);
Array(100).fill(1).map((value, index) => (value+index)**2);
Enter fullscreen mode Exit fullscreen mode

Don't forget to wrap if there are multiple things to be calculated

2**3**2;
// 512
(2**3)**2;  // this is what I wanted
// 64
Enter fullscreen mode Exit fullscreen mode

Math.pow()

Math.pow() function returns the base to the exponent power, as in base^exponent.

Math.pow(9, 3);
// 729

(2**3)**2;
// 64
Math.pow(Math.pow(2,3),2); // (2^3)^2 // (2*2*2)*(2*2*2)
// 64
Enter fullscreen mode Exit fullscreen mode

split()

split() is a method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.

// syntax
split()
split(separator)
split(separator, limit)

let str = 'I watched a movie called "The Grand Budapest Hotel" last night';

str.split(' ', 2);
// ['I', 'watched']

const words = str.split(' ');
console.log(words[3]);
// movie

const chars = str.split('');
console.log(chars[8]);
// d

const strCopy = str.split();
// console.log(strCopy);
// ['I watched a movie called "The Grand Budapest Hotel" last night']


'.'.split('.');
// ['', '']
'.'.repeat(9).split('.');
// ['', '', '', '', '', '', '', '', '', '',]
let str = "I am Hailey"
str.split(' ');
// ['I', 'am', 'Hailey']

let str = "I am Hailey.J"
str.split(' ');
// ['I', 'am', 'Hailey.J']
str.split('.');
// ['I am Hailey', 'J ']
str.split(/\s/) //split by space
// ['I', 'am', 'Hailey.J']
str.split('');
// ['I', '', 'a', 'm', '', 'H', 'a', 'i', 'l', 'e', 'y', '.', 'J']'

'12367'.split('');
// ['1', '2', '3', '6', '7']
'12367'.split('').forEach(x => x)
// undefined // forEach doesn't return the value, it only execute the function.
let a = '12367'.split('');
a;
// ['1', '2', '3', '6', '7']
a.map(x => parseInt(x)); // string to number
// [1, 2, 3, 6, 7]

'12367'.split('').map(x => parseInt(x)).forEach(x => console.log(x));
// 1
// 2
// 3
// 6
// 7

let sum = 0;
'12367'.split('').map(value => parseInt(value)).forEach(value => sum += value);
sum;
// 19

'12367'.split('').map(value => parseInt(value));
// [1, 2, 3, 6, 7]
'12367'.split('').map(value => value + value);
// ['11', '22' '33', '66', '77']

let sum = 0;
[1, 2, 3, 6, 7].forEach(value => sum += value);
// 19
Enter fullscreen mode Exit fullscreen mode

'12367' was string but using .split(''), it's split strings and through map, it's iterated
'12367' was string but it becomes an array after using .split(''), so you can use map() or forEach()

Difference between map() and forEach()

map(): returns array of callback function (it doesn't effect or change the original array)
forEachO): doesn't return value and it just execute the provided callback function once for each array element.

let array1 = [1, 3, 6];

array1.map(num => console.log(num * 2));
// 2
// 6
// 12
let map1 = array1.map(num => num * 2);
console.log(map1);
// [2, 6, 12]

array1.forEach(num => console.log(num * 2));
// 2
// 6
// 12
let forEach1 = array1.forEach(num => num * 2);
console.log(forEach1);
//undefined
Enter fullscreen mode Exit fullscreen mode

toString(), toLcaleString(), toTimeString(), toISOString()

toString(): returns a string representing the object
toLocaleString(): returns a string with a language
toTimeString(): returns the time portion of a Date object in human readable form in English.sensitive representation of this date.
toISOString(): returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively)

about "new"

let today = new Date('2021/12/7/12:00');
// "new" creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

today;
// Tue Dec 07 2021 12:00:00 GMT+0900 (한국 표준시)
today.toString();
// 'Tue Dec 07 2021 12:00:00 GMT+0900 (한국 표준시)'
today.toLocaleDateString();
// '2021. 12. 7.'
today.toLocaleString();
// '2021. 12. 7. 오후 12:00:00'
today.toLocaleString('ko-KR');
// '2021. 12. 7. 오후 12:00:00'
today.toLocaleString('en-US');
// '12/7/2021, 12:00:00 PM'
today.toTimeString();
// '12:00:00 GMT+0900 (한국 표준시)'
today.toISOString();
// '2021-12-07T03:00:00.000Z'
today.toISOString().slice(0,10);
// '2021-12-07'
today.toISOString().slice(0,4);
// '2021'
today.toISOString().slice(5,7);
// '12'
today.toISOString().slice(8,10);
// '07'

today.toISOString().slice(0,10).split('-');
// ['2021', '12', '07']
today.toISOString().slice(0,10).split('-').map(value => parseInt(value));
// [2021, 12, 7]
Enter fullscreen mode Exit fullscreen mode

lang code: http://www.lingoes.net/en/translator/langcode.htm

Instead of above code, you can use instance methods of Date

// let today = new Date()
let date = new Date('2013-08-03T02:00:00Z');
let year = date.getFullYear();
let month = date.getMonth()+1;
let dt = date.getDate();
Enter fullscreen mode Exit fullscreen mode

About Date

Math.ceil(), Math.floor(), Math.round(), Math.PI

Math.ceil(): always rounds a number up to the next largest integer.
NOTE Math.ceil(null) returns integer 0 and does not give a NaN error.
Math.floor() returns the largest integer less than or equal to a given number.
Math.round() returns the value of a number rounded to the nearest integer.
Math.PI: represents the ratio of the circumference of a circle to its diameter, approximately 3.14159:

Math.ceil(9.5);
// 10
Math.ceil(9.2);
// 10
Math.ceil(-9.2);
// -9
Math.floor(0.3);
// 0
Math.floor(0.9);
// 0
Math.floor(-9.2);
// -10
Math.round(3.5);
// 4
Math.round(3.6);
// 4
Math.round(3.4);
// 3
Math.PI;
// 3.141592653589793
Enter fullscreen mode Exit fullscreen mode

Math.max(), Math.min()

Math.max() returns the largest of the zero or more numbers given as input parameters, or NaN if any parameter isn't a number and can't be converted into one.
Math.min() returns the lowest-valued number passed into it, or NaN if any parameter isn't a number and can't be converted into one.

Math.max();
// -Infinity
Math.min();
// Infinity
Math.max(1,2,3,4);
// 4
Math.max([1,10, 2, 7]); 
// NaN
Math.max(...[1, 10, 2, 7]); // use spread operator!
// 10
Math.max.apply(null, [1, 2, 10, 6, 7]);
// 10

Enter fullscreen mode Exit fullscreen mode

About spread operator

reduce()

reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
syntax

let value = arr.reduce(function(accumulator, item, index, array) {
  // ...
}, [initial]);
Enter fullscreen mode Exit fullscreen mode
let arr = [1, 2, 3, 4, 5];

let result = arr.reduce((sum, current) => sum += current, 0); // the number after current here which is 0 -> it's like starting value if it is 2, it returns 17 not 15
console.log(result);
// 15
// 0 + 1 = 1 (because it gave the  initial value 0 so it starts from 0) and current num(item) = 1
// 1 + 2 = 3
// 3 + 3 = 6
// 6+ 4 = 10
// 10 + 5 = 15

let result = arr.reduce((sum, current) => sum += current);
console.log(result);
// 15

// you can write about code using forEach this way
let arr = [1, 2, 3, 4, 5]
let sum =0
arr.forEach(i=> sum += i)
console.log(sum)
// 15

let multiply = arr.reduce((sum, current) => sum *= current); // sum here is accumulator
console.log(multiply);
// 120
Enter fullscreen mode Exit fullscreen mode

Number.EPSILON

Number.EPSILON property represents the difference between 1 and the smallest floating point number greater than 1.
This is effectively the maximum possible rounding error for floating point numbers.

0.3+0.6;
// 0.8999999999999999
Number.MAX_SAFE_INTEGER;
// 9007199254740991
Number.MAX_SAFE_INTEGER;
// 9007199254740991
Number.EPSILON;
// 2.220446049250313e-16
Enter fullscreen mode Exit fullscreen mode

Bigint

BigInt is a primitive wrapper object used to represent and manipulate primitive bigint valueswhich are too large to be represented by the number primitive.
A BigInt value, also sometimes just called a BigInt, is a bigint primitive, created by appending n to the end of an integer literal, or by calling the BigInt() constructor (but without the new operator) and giving it an integer value or string value.

9007199254740991 + 1;  
// 9007199254740992
9007199254740991 + 2; // the number is incorrect
// 9007199254740992
9007199254740991 + 3
// 9007199254740994
9007199254740991 + 4 // the number is incorrect
// 9007199254740996

9007199254740991n + 4n; // Bigint using 'n' to the end of an integer. This way, it calculates the big numbers correctly
// 9007199254740995n
Enter fullscreen mode Exit fullscreen mode

flat()

flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

// flat(depth)

[1, 2, 3, 4, [1, 2, 3]].flat();
// [1, 2, 3, 4, 1, 2, 3]
[1, 2, 3, 4, [1, 2, 3]].flat(1);
// [1, 2, 3, 4, 1, 2, 3]
[1, 2, 3, 4, [1, 2, 3]].flat(2);
// [1, 2, 3, 4, 1, 2, 3]
[1, 2, 3, 4, [1, 2, [1, 2, 3]]].flat();  // default value is one. one depth
// [1, 2, 3, 4, 1, 2, Array(3)]
[1, 2, 3, 4, [1, 2, [1, 2, 3]]].flat();
// [1, 2, 3, 4, 1, 2, Array(3)]
[1, 2, 3, 4, [1, 2, [1, 2, 3]]].flat(2);
// [1, 2, 3, 4, 1, 2, 1, 2, 3]
[1, 2, 3, 4, [1, 2, [1, 2, 3]]].flat().flat();
// [1, 2, 3, 4, 1, 2, 1, 2, 3]
[1, 2, 3, 4, [1, 2, [1, 2, 3]]].flat(Infinity);
// [1, 2, 3, 4, 1, 2, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

"use strict" / strict mode

About strict mode

function test() {
 x = 10
}
test()
console.log(x)
// 10
x;
// 10
Enter fullscreen mode Exit fullscreen mode

How come above code works? Why does it console.log(x) and how can I access to it?
Because x is value declared inside function and it's not supposed to be accessed from outside.
Then how can I make it unable to do it and throw an error?
by using strict mode: 'use strict' or "use strict"
use stric
Now you can't access to it.
About "use strict"

this

practice

let hotel = [{
  'name' : 'one hotel',
  'location' : 'Gangnam, Seoul',
  'price' : {'A':50000, 'B':30000, 'C':15000},
  'rooms' : 50,
  'reservation' : 25,
  'left rooms' : function(){return this.rooms - this.reservation}
},{
  'name' : 'two hotel',
  'location' : 'Mapo, Seoul',
  'price' : {'A':100000, 'B':60000, 'C':30000},
  'rooms' : 100,
  'reservation' : 30,
  'left rooms' : function(){return this.rooms - this.reservation}
},{
  'name' : 'three hotel',
  'location' : 'Gangnam, Seoul',
  'price' : {'A':80000, 'B':50000, 'C':30000},
  'rooms' : 120,
  'reservation' : 80,
  'left rooms' : function(){return this.rooms - this.reservation}
}];
// assigned function to left rooms because the value will be dynamically updated.

hotel[0];
// {name: 'one hotel', location: 'Gangnam, Seoul', price: {…}, rooms: 50, reservation: 25, …}
hotel[0]['left rooms']();
// 25
hotel[0]['left rooms']; // it's because of function
// ƒ (){return this.rooms - this.reservation}
hotel[0]['reservation'] = 49;
// 49
hotel[0]['left rooms']();
// 1
Enter fullscreen mode Exit fullscreen mode

JSON(JavaScript Object Notation)

JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON.
JSON is a text format for storing and transporting data. It can't be called or constructed, and aside from its two method properties, it has no interesting functionality of its own.

let student = {
    name: 'Hailey',
    age: 20,
    isAdmin: false,
    courses: ['html', 'css', 'js'],
    hobby: null
};

let json = JSON.stringify(student);

json;
// '{"name":"Hailey","age":20,"isAdmin":false,"courses":["html","css","js"],"hobby":null}'

JSON.stringify("test")
// '"test"'

let user = {
    name: 'John',
    age: 25,
    roles: {
        isAdmin: false,
        isEditor: true,
    }
};

console.log(JSON.stringify(user, null, 4));
//{
    "name": "John",
    "age": 25,
    "roles": {
        "isAdmin": false,
        "isEditor": true
    }
}

Enter fullscreen mode Exit fullscreen mode

JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

let numbers = "[0, 1, 2, 3]";

numbers = JSON.parse(numbers);
// [0, 1, 2, 3]
numbers[1]
// 1
Enter fullscreen mode Exit fullscreen mode

JSON generator

JSON generator: https://json-generator.com/

sort()

let data = [20, 10, 1, 2, 3, 6, 4, 22, 33, 11];

// Ascending
data.sort(function(a,b) {
    if(a > b) {
        return 1;
    }
    if(a < b) {
        return -1;
    }
    return 0;
})
// [1, 2, 3, 4, 6, 10, 11, 20, 22, 33]


//Descending
data.sort(function(a,b) {
    if(a < b) {
        return 1;
    }
    if(a > b) {
        return -1;
    }
    return 0;
})
// [33, 22, 20, 11, 10, 6, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)