-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patharrays-to-objects.js
More file actions
126 lines (93 loc) · 2.37 KB
/
Copy patharrays-to-objects.js
File metadata and controls
126 lines (93 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
//: Creating an array of objects
let cars = [
{
color: "red",
type: "minivan",
registration: new Date("2017-01-01"),
capacity: 10,
},
{
color: "green",
type: "van",
registration: new Date("2018-01-01"),
capacity: 15,
},
{
color: "yellow",
type: "truck",
registration: new Date("2012-01-01"),
capacity: 50,
},
];
//* Add a new object at the start Array.unshift
cars.unshift({
color: "purple",
type: "turbo",
registration: new Date("2021-01-01"),
capacity: 30,
});
console.log(cars);
//* Add a new object at the end - Array.push()
cars.push({
color: "black",
type: "car",
registration: new Date("2025-01-01"),
capacity: 2,
});
//* Add a new object in the middle Array.slice
/** Array.slice(
{index where to start},
{how many item to remove},
{item to add}
) */
cars.splice(2, 0, {
color: "white",
type: "helicopter",
registration: new Date("2019-01-01"),
capacity: 4,
});
//* Find an object in an array by its values - Array.find
let car = cars.find((car) => car.color === "white");
//? It's also possible to search for multiple values:
let car2 = cars.find((car) => car.color === "red" && car.type === "minivan");
console.log(car2);
//* Get multiple items from an array that match a condition - Array.filter
const redCars = cars.filter((car) => car.color === "red");
//* Transform objects of an array - Array.map
let sizes = cars.map((car) => {
if (car.capacity <= 2) {
return "small";
}
if (car.capacity <= 4) {
return "medium";
}
return "large";
});
console.log(sizes);
//? It's also possible to create a new object if we need more values
let carsProperties = cars.map((car) => {
let properties = {
capacity: car.capacity,
size: "large",
};
if (car.capacity <= 2) {
properties["size"] = "small";
}
if (car.capacity <= 4) {
properties["size"] = "medium";
}
return properties;
});
console.log(carsProperties);
//* Sort an array by a property - Array.sort
let sortedCars = cars.sort((c1, c2) =>
c1.capacity < c2.capacity ? 1 : c1.capacity > c2.capacity ? -1 : 0
);
console.log(sortedCars);
//* Checking if objects in array fulfill a condition - Array.every, array.includes
let carsEvery = cars.every(
(car) => car.color === "red" && car.type === "minivan"
);
let carsSome = cars.some(
(car) => car.color === "red" && car.type === "minivan"
);