Skip to content

Array methods: Changed task 3 and 11 solutions code #3783

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
function unique(arr) {
let result = [];
const uniqueArr = [];

arr.forEach(item => uniqueArr.includes(item) ? null : uniqueArr.push(item));
return uniqueArr;

for (let str of arr) {
if (!result.includes(str)) {
result.push(str);
}
}

return result;
}
12 changes: 4 additions & 8 deletions 1-js/05-data-types/05-array-methods/11-array-unique/solution.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,11 @@ Let's walk the array items:

```js run demo
function unique(arr) {
let result = [];
const result = [];

for (let str of arr) {
if (!result.includes(str)) {
result.push(str);
}
}
arr.forEach(item => result.includes(item) ? null : result.push(item));
return result;

return result;
}

let strings = ["Hare", "Krishna", "Hare", "Krishna",
Expand All @@ -30,7 +26,7 @@ So if there are `100` elements in `result` and no one matches `str`, then it wil

That's not a problem by itself, because JavaScript engines are very fast, so walk `10000` array is a matter of microseconds.

But we do such test for each element of `arr`, in the `for` loop.
But we do such test for each element of `arr`, in the `forEach` method.

So if `arr.length` is `10000` we'll have something like `10000*10000` = 100 millions of comparisons. That's a lot.

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@

function filterRangeInPlace(arr, a, b) {

for (let i = 0; i < arr.length; i++) {
let val = arr[i];

// remove if outside of the interval
if (val < a || val > b) {
arr.splice(i, 1);
i--;
}
}
arr
.filter(value => value < a || value > b)
.forEach(value => arr.splice(arr.indexOf(value), 1));

}
Original file line number Diff line number Diff line change
@@ -1,15 +1,9 @@
```js run demo
function filterRangeInPlace(arr, a, b) {

for (let i = 0; i < arr.length; i++) {
let val = arr[i];

// remove if outside of the interval
if (val < a || val > b) {
arr.splice(i, 1);
i--;
}
}
arr
.filter(value => value < a || value > b)
.forEach(value => arr.splice(arr.indexOf(value), 1));

}

Expand Down