Categories
JavaScript Answers

How to Filter a JavaScript Array from All Elements of Another Array?

Sometimes, we want to filter a JavaScript array from all elements of another JavaScript array.

In this article, we’ll look at how to filter a JavaScript array from all elements of another array.

Using the Array.prototype.filter Method

We can use the JavaScript array filter method to filter out the array entries that are entries of another array.

For instance, we can write:

const filtered = [1, 2, 3, 4].filter(
  function(e) {
    return this.indexOf(e) < 0;
  },
  [2, 4]
);
console.log(filtered);

to do so.

We call filter on [1, 2, 3, 4] with a callback that calls this.indexOf(e) < 0 and return the result.

We set the value of this in the callback with the 2nd argument of filter .

Therefore, this is [2, 4] .

And so filtered is [1, 3] .

We cam also use the includes method to filter out the items that are in the other array.

For instance, we can write:

const filtered = [1, 2, 3, 4].filter(
  function(e) {
    return !this.includes(e);
  },
  [2, 4]
);
console.log(filtered);

And we get the same result for filter .

We can replace the callback with an array function if we don’t use this inside the callback.

To do this, we can write:

const filtered = [1, 2, 3, 4].filter(
  (e) => {
    return [2, 4].indexOf(e) < 0;
  }
);
console.log(filtered);

or:

const filtered = [1, 2, 3, 4].filter(
  (e) => {
    return ![2, 4].includes(e);
  }
);
console.log(filtered);

We replace this with the array itself.

And we get the same result.

Conclusion

We can use the JavaScript array filter instance method to return an array that has the items that are included in another array filtered out.

Categories
JavaScript Answers

How to Loop for x Times with JavaScript without Using a Mutable Variable?

Sometimes, we want to run code repeatedly for x times with JavaScript without using a mutable variable.

In this article, we’ll look at how to run code repeatedly for x times with JavaScript without using a mutable variable.

Using the Array Constructor, Spread Operator, and Array.prototype.map

We can create an array with length x with the Array constructor, and then call the map method to return the result we want.

For instance, we can write:

const res = [...Array(10)].map((_, i) => {
  return i * 10;
});
console.log(res)

We create an array with 10 empty slots with Array(10) .

Then we spread that into a new array, then we call map to return the element we want in the returned array.

We get the index i , multiply it by 10 and return it.

Therefore, res is:

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

Using the Array Constructor, Spread Operator, and Array.prototype.forEach

If we don’t want to return a new array after running our code repeatedly, we can also call the forEach method on the empty array instead of map .

For example, we can write:

[...Array(10)].forEach((_, i) => {
  console.log(i);
});

We just log the index i value in the forEach callback.

And so we get 0, 1, 2,…, all the way up to 9 logged from the console log.

Using the Array.from Method

We can also sue the Array.from method to create an empty array and then use Array.prototype.map to map the empty array into an array of values we want.

For instance, we can write:

const res = Array.from(Array(10)).map((_, i) => {
  return i * 10;
});
console.log(res)

And then we get the same result as the first example.

Conclusion

We can run code repeatedly for x times without create a loop with a mutable index variable with JavaScript array methods and the spread operator.

Categories
JavaScript Answers

How to Transform a JavaScript Iterator into a JavaScript Array?

Sometimes, we have an iterator object in our JavaScript code that we want to convert into an array.

In this article, we’ll look at how to transform a JavaScript iterator into a JavaScript array.

Using the Array.from Method

One way to transform JavaScript iterator into a JavaScript array is to use the Array.from static method.

For instance, we can write:

const map = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3],
])
const arr = Array.from(map.entries());
console.log(arr)

We create a Map instance which has the entries method that returns an iterator that returns the key-value pairs from the map.

Then we pass the returned iterator from the entries method into the Array.from method to return an array of key-value pair arrays from the iterator.

Therefore, the value of arr is:

[
  [
    "a",
    1
  ],
  [
    "b",
    2
  ],
  [
    "c",
    3
  ]
]

Using the Spread Operator

We can do the same thing that Array.from method does with the spread operator.

It also lets us convert iterator objects to arrays.

For instance, we can write:

const map = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3],
])
const arr = [...map.entries()];
console.log(arr)

to spread the iterator returned by map.entries into an array.

The key-value pair arrays are spread into the arr array.

Therefore, arr is once again:

[
  [
    "a",
    1
  ],
  [
    "b",
    2
  ],
  [
    "c",
    3
  ]
]

which is the same as the previous example.

Conclusion

We can convert JavaScript iterator objects easily into JavaScript arrays with the Array.from method or the spread operator.

Categories
JavaScript Answers

How to Execute JavaScript Code Stored in a String?

Sometimes, we have a JavaScript string with code in it that we want to run.

In this article, we’ll look at how to execute JavaScript code stored in a string.

Create a New Function with the Function Constructor

We can create a new function from our JavaScript code string with the Function constructor.

For instance, we can write:

const code = "alert('Hello World'); let x = 100";  
const F = new Function(code);  
F();

to create the code string and store it into the code variable.

Then we pass code into the Function constructor to create a function from it.

And then we call F to run the function.

Use the setTimeout Function

We can also pass in the JavaScript code string into the setTimeout function to run the code string.

To do this, we write:

const code = "alert('Hello World'); let x = 100";  
setTimeout(code, 1);

We pass code as the first argument of the setTimeout function to run it.

The 2nd argument is the delay in milliseconds before running the function.

Don’t Use the eval Function

We shouldn’t use the eval function to run code from a string.

This is because anyone can easily inject code into it, which is a big security risk.

Also, it creates its own scope, which means it may do things we don’t expect.

So we shouldn’t write code like:

const code = "alert('Hello World'); let x = 100";  
eval(code)

in our JavaScript code.

Conclusion

We can run JavaScript code that’s stored in a string with JavaScript by creating a function from it with the Function constructor or pass it into the setTimeout function.

Categories
JavaScript Answers

How to Append HTML to a Container Element without Setting innerHTML with JavaScript?

Oftentimes, we want to append HTML content into a container element.

Sometimes, we want to do this without setting the innerHTML property of the container element to do so.

In this article, we’ll look at how to append HTML to a container element without setting the innerHTML property of the container element with JavaScript.

Use document.createElement and appendChild

One way to add child elements to a container element without setting the innerHTML property is to use the document.createElement method to create the element.

Then we can call appendChild to append the element.

For instance, if we have the following HTML:

<div>

</div>

Then we can write:

const element = document.querySelector('div')
const e = document.createElement('div');
const htmldata = 'hello world'
e.innerHTML = htmldata;

while (e.firstChild) {
  element.appendChild(e.firstChild);
}

We get the div that we added with querySelector .

Then we call document.createElement to create another div that we insert into the parent div as a child element.

We set e.innerHTML ‘s value of the newly created element to add some content into it.

And then we call element.appendChild to add the child element into the div we initially added.

Now we should see ‘hello world’ on the screen.

Use the insertAdjacentHTML Method

Another way to insert a child element into a container element as a child element is to use the insertAdjacentHTML method.

If we have the following HTML:

<div>

</div>

Then we can use it by writing:

const element = document.querySelector('div')
element.insertAdjacentHTML('beforeend', '<div>hello world</div>');

We get the div with querySelector .

Then we call insertAdjacentHTML with 'beforeend' and the HTML we want to insert into the div as arguments.

Now we should see the same result as the previous example.

Conclusion

We can append HTML to a container element without setting innerHTML with JavaScript by using various methods available in DOM element objects.