Skip to content

Commit ad91a4d

Browse files
committed
improved exmample for arrays
1 parent f58ecd3 commit ad91a4d

File tree

1 file changed

+8
-29
lines changed

1 file changed

+8
-29
lines changed

JavaScript-Quick-Reference.md

+8-29
Original file line numberDiff line numberDiff line change
@@ -401,42 +401,21 @@ Detailed guide on JavaScript Arrays, covering array manipulation methods, iterat
401401
- `array.splice(start, deleteCount, element1, element2)` Adds and/or removes elements from an array.
402402
- `arr.unShift("element1", "element2");` Adds one or more elements to the front of an array and returns the new length of the array.
403403

404-
### Example of arrray.sort()
404+
### Example of .sort() & .filter()
405405

406406
```javascript
407-
// Assume we have an array of objects with a 'category' property
408-
const items = [
409-
{ name: 'Banana', category: 'Fruit' },
410-
{ name: 'Carrot', category: 'Vegetable' },
411-
{ name: 'Apple', category: 'Fruit' },
412-
{ name: 'Lettuce', category: 'Vegetable' },
413-
{ name: 'Orange', category: 'Fruit' }
414-
];
415-
416-
// Sort the items by category in ascending order
417-
items.sort((a, b) => {
418-
if (a.category < b.category) {
419-
return -1;
420-
}
421-
if (a.category > b.category) {
422-
return 1;
423-
}
424-
return 0;
425-
});
407+
let numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
408+
409+
let result = numbers
410+
.sort((a, b) => a - b) // Sort in ascending order
411+
.filter(number => number > 3); // Filter numbers greater than 3
426412

427-
console.log(items);
413+
console.log(result); // [4, 4, 5, 5, 5, 6, 9]
428414

429-
// Outputs:
430-
[
431-
{ name: 'Banana', category: 'Fruit' },
432-
{ name: 'Apple', category: 'Fruit' },
433-
{ name: 'Orange', category: 'Fruit' },
434-
{ name: 'Carrot', category: 'Vegetable' },
435-
{ name: 'Lettuce', category: 'Vegetable' }
436-
]
437415
```
438416

439417
### Acessor Methods
418+
- `array.filter(callback[, thisArg])` Creates a new array containing elements that meet a specified condition defined by the provided callback function.
440419
- `array.at(index)` Returns the element at the specified index in the array.
441420
- `array.concat(value1, value2, array2)` Returns a new array comprised of this array joined with other array(s) and/or value(s).
442421
- `array.includes(searchElement, fromIndex)` Determines whether an array contains a certain element, returning true or false as appropriate.

0 commit comments

Comments
 (0)