Skip to content

Commit ced2268

Browse files
committed
adding new Javascript problems and techniques
1 parent fa49727 commit ced2268

35 files changed

+1709
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
### General Object Destructuring Example
2+
3+
```js
4+
let myObj = {
5+
name: "Luke",
6+
age: 25,
7+
hobbies: "music"
8+
};
9+
10+
let { name, age, hobbies } = myObj;
11+
12+
console.log(name, age, hobbies); // => Luke 25 music
13+
```
14+
15+
Now the variables listed in between the curly braces are assigned the value of their respective properties in myObj.
16+
17+
### The order in which the variables are listed in the curly braces doesn’t matter. Additionally, we don’t have to list all the properties of an object if we only need one or two.
18+
19+
```js
20+
console.log(age, name, hobbies); // => 25 'Luke' 'music'
21+
22+
console.log(hobbies, name, age); // => music Luke 25
23+
24+
console.log(hobbies, name); // => music Luke
25+
26+
```
27+
28+
### General Array Destructuring Example
29+
30+
```js
31+
let arr = [‘Jim’, ‘Bob’, ‘Sarah’, ‘Cassie’];
32+
33+
let [ jim, bob, sarah, cassie ] = arr;
34+
35+
console.log(jim, bob, sarah, cassie); //outputs: Jim Bob Sarah Cassie
36+
```
37+
38+
## Unlike objects, the name we give the variables doesn’t matter. Let’s change the above example: So, each of the variable names will ONLY count for the index-positions I fetch.
39+
40+
```js
41+
let arr = [‘Jim’, ‘Bob’, ‘Sarah’, ‘Cassie’];
42+
43+
let [ var1, var2, var3, var4] = arr;
44+
45+
console.log(var1, var2, var3, var4); //outputs: Jim Bob Sarah Cassie
46+
```
47+
48+
### If I include less variables then there are indexes in the arrays, then just like in Object-destructuring, only that many array element will be included in the returned array, starting from zero-index position and AGAIN without giving any meaning to the the name I give to the variables. So, each of the variable names will ONLY count for the index-positions I fetch.
49+
50+
let arr = [‘Jim’, ‘Bob’, ‘Sarah’, ‘Cassie’];
51+
52+
let [ jim, bob, cassie ] = arr;
53+
54+
console.log(jim, bob, cassie); //outputs: Jim Bob Sarah
55+
56+
## Using Spread operator - It is often used for splitting out a part of an object, but keeping the remaining properties in another object.
57+
58+
```js
59+
let myObj = {
60+
61+
name: "Luke",
62+
age: 25,
63+
hobbies: "music"
64+
65+
};
66+
67+
let { hobbies, ...rest } = myObj; // => Luke 25 music
68+
69+
console.log(hobbies, rest) // => music { name: 'Luke', age: 25 }
70+
71+
console.log(hobbies, rest.age) // => music 25
72+
73+
```
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class User {
2+
3+
constructor (name, age) {
4+
this.name = name;
5+
this.age = age;
6+
}
7+
8+
getUserData() {
9+
console.log(this.name + " is " + this.age + " years old.");
10+
}
11+
}
12+
13+
let user = new User('paul', 18)
14+
user.getUserData()
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
//Destructuring Example-1
2+
/* Destructuring allows us to extract data from arrays and objects into separate variables.
3+
4+
Destructuring can also be used for passing objects into a function, allowing you to pull specific properties out of an object in a concise manner. It is also possible to assign default values to destructured arguments, which can be a useful pattern if passing in a configuration object. */
5+
6+
let jane = { firstName: 'Jane', lastName: 'Doe'};
7+
let john = { firstName: 'John', lastName: 'Doe', middleName: 'Smith' }
8+
9+
// the below pattern that I always use in React
10+
let sayName = ({firstName, lastName, middleName = "N/A"}) => {
11+
console.log(`Hello ${firstName} ${lastName} ${middleName}`);
12+
}
13+
14+
// sayName(jane); // -> Hello Jane N/A Doe
15+
// sayName(john) // -> Hello John Doe Smith
16+
17+
// Examples of array destructuring for function parameters:
18+
function foo ( [x, y] ) {
19+
console.log(x, y);
20+
}
21+
22+
// foo([1,2]); // -> 1 2
23+
// foo([2]); // -> 2 undefined
24+
// foo([]) // -> undefined undefined
25+
26+
27+
// Examples of Object destructuring for parameters in function declaration:
28+
29+
function foo ( { x, y } ) {
30+
console.log(x, y);
31+
}
32+
33+
foo({y: 1, x: 2}) // -> 2 1
34+
35+
foo({y: 1}) // -> undefined 1
36+
37+
foo({}) // -> undefined undefined
38+
39+
/* This technique is an approximation of named arguments, in that the properties on the object map to the destructured parameters of the same names. That also means that we get optional parameters (in any position) for free, as you can see leaving off the x "parameter" worked as we'd expect. */
40+
41+
42+
//Destructuring Example-2
43+
44+
let full_name =['John','Deo'];
45+
46+
let [first_name,last_name]=full_name;
47+
48+
console.log(first_name,last_name);
49+
// outputs John Deo
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/*every:
2+
3+
callback is a predicate - it should return a truthy or falsy value
4+
callback answers: does this item meet your criteria?
5+
callback gets these arguments: item, index, list
6+
final return value: false after the first item that failed to meet your criteria, else true
7+
note: stops iterating once it receives a falsy value from your callback.
8+
example use case:*/
9+
10+
const allPositiveNumbers = [1 , 2, 3].every((item) => {
11+
return item > 0;
12+
})
13+
14+
console.log(allPositiveNumbers);
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Problem-1 Filter even numbers
2+
3+
let numberArray = [1,2,3,4,5,6,7,8,9,10];
4+
5+
let evenNumbers = [];
6+
7+
for (let i = 0; i < numberArray.length; i++) {
8+
if (numberArray[i] % 2 === 0) {
9+
evenNumbers.push(numberArray[i]);
10+
}
11+
}
12+
// console.log(evenNumbers);
13+
14+
let evenNumbersWithFilter = numberArray.filter((item) => (item % 2 === 0));
15+
16+
// console.log(evenNumbersWithFilter);
17+
18+
19+
// Problem 2:- Filter objects with tags javascript
20+
21+
var persons = [
22+
{id : 1, name : "John", tags : "javascript"},
23+
{id : 2, name : "Alice", tags : "javascript"},
24+
{id : 3, name : "Roger", tags : "java"},
25+
{id : 4, name : "Adam", tags : "javascript"},
26+
{id : 5, name : "Alex", tags : "java"}
27+
];
28+
29+
let jsTags = persons.filter((item) => (item.tags === "javascript"))
30+
31+
// console.log(jsTags);
32+
33+
// Problem 2 with indexOf
34+
let jsTags2 = persons.filter((item) => (item.tags.indexOf("javascript") > -1));
35+
36+
// console.log(jsTags2);
37+
38+
// Other example - traverses an array and inserts non-duplicate elements into a new array. That is, if an element is duplicated, then only insert that element once into the final newArray
39+
40+
function findNonDuplicates (array) {
41+
let models = [];
42+
for(var i = 0; i < array.length; i++) {
43+
if(array.indexOf(array[i]) === i) {
44+
models.push(array[i]);
45+
}
46+
}
47+
return models;
48+
}
49+
50+
let arr = [1, 2, 3, 4.4, 2];
51+
// console.log(findNonDuplicates((arr)));
52+
53+
// using filter
54+
function findNonDuplicatesFilter (array) {
55+
return array.filter((elem, index, arr) => {
56+
return array.indexOf(elem) === index;
57+
})
58+
}
59+
60+
// console.log(findNonDuplicatesFilter(arr));
61+
62+
// Write a function that returns the number of zeros in a given array?
63+
noOfZeros = arr => {
64+
return arr.filter(zero => (zero === 0)).length
65+
}
66+
67+
console.log(noOfZeros([1, 2, 0, 0, 5]));
68+
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
3+
find () - arguments explanation
4+
5+
callback is a predicate - it should return a truthy or falsy value
6+
callback answers: is this item what you’re looking for?
7+
callback gets these arguments: item, index, list
8+
final return value: the item you’re looking for, or undefined
9+
note: stops iterating once it receives a truthy value from your callback.
10+
example use case
11+
12+
13+
findIndex:
14+
15+
callback is a predicate - it should return a truthy or falsy value
16+
callback answers: is this item what you’re looking for?
17+
callback gets these arguments: item, index, list
18+
final return value: the index of the item you’re looking for, or -1
19+
note: stops iterating once it receives a truthy value from your callback.
20+
example use case:*/
21+
22+
23+
// Examaple to find negaive number
24+
function findNegativeNum (elem) {
25+
return elem < 0;
26+
}
27+
28+
let myArr = [1, 20, false, -2];
29+
30+
// find method returns first negative number found
31+
// console.log(myArr.find(findNegativeNum)); // -2
32+
33+
// findIndex method returns index of first negative number located
34+
// console.log(myArr.findIndex(findNegativeNum)); // 3
35+
36+
// example function to find non-numeric array values
37+
function findNonNum(elem) {
38+
return typeof elem !== 'number' ;
39+
}
40+
41+
let myArr1 = [2, 27, 33.45, 'apple', 'yes', 0, 3.14];
42+
43+
// find method returns value of first non-numeric element
44+
// console.log(myArr1.find(findNonNum));
45+
// findIndex returns location of first non-numeric element
46+
// console.log(myArr1.findIndex(findNonNum));
47+
48+
// another example array to search for non-numeric values
49+
let myArr3 = [1, 2, 3, 4.4];
50+
51+
// console.log(myArr3.find(findNonNum)); // returns undefined
52+
// console.log(myArr3.findIndex(findNonNum)); // returns -1
53+
54+
55+
const objects = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];
56+
57+
const findIdWithb = objects.find((item) => {
58+
return item.id === 'b'
59+
});
60+
61+
console.log(findIdWithb);
62+
63+
const findIdIndexWithb = objects.findIndex((item) => {
64+
return item.id === 'b'
65+
});
66+
67+
console.log(findIdIndexWithb);
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// The map() method creates a new array with the results of calling a provided function on every element in this array.
2+
3+
// Problem - 1 We’ve an array of products, that has two properties: `id` and `name`. I want to get all ids, wih map() method:
4+
5+
let products = [
6+
{
7+
id: 0,
8+
name: 'Product 1'
9+
},
10+
{
11+
id: 1,
12+
name: 'Product 2'
13+
}
14+
];
15+
16+
let productsIds = products.map((item) => {
17+
return item.id;
18+
})
19+
20+
// console.log(productsIds);
21+
22+
/* Problem-2
23+
24+
The map() mehod's syntax is as below
25+
26+
let newArr = oldArr.map((val, index, arr) => {
27+
// return element to new Array
28+
});
29+
30+
newArr — the new array that is returned
31+
oldArr — the array to run the map function on
32+
val — the current value being processed
33+
index — the current index of the value being processed
34+
arr — the original array
35+
36+
Create an object from a given array and the given array is as below
37+
[1,2,3,4];
38+
39+
*/
40+
41+
let arr = [1,2,3,4];
42+
43+
let obj = arr.map((val, index, arr) => {
44+
return {
45+
VALUE : val,
46+
INDEX: index
47+
}
48+
})
49+
50+
// console.log(obj);
51+
52+
// Problem-2 - Using map() return full name from the given array
53+
var oldArr = [{first_name:"Colin",last_name:"Toh"},{first_name:"Addy",last_name:"Osmani"},{first_name:"Yehuda",last_name:"Katz"}];
54+
55+
let newArr = [];
56+
57+
oldArr.map((item, index) => {
58+
item.full_name = [item.first_name, item.last_name].join(' ');
59+
return item;
60+
});
61+
console.log(oldArr);

0 commit comments

Comments
 (0)