Categories
JavaScript Answers

How to Compute the Intersection of Two Arrays in JavaScript?

To compute the intersection of two arrays in JavaScript, we can use the array filter method with the includes method to get the elements that are in both arrays and return them in an array.

For instance, we can write:

const arr1 = ["mike", "sue", "tom", "kathy", "henry"];
const arr2 = ["howey", "jim", "sue", "jennifer", "kathy", "hank", "alex"];

const result = arr1.filter((n) => {
  return arr2.includes(n);
});
console.log(result)

to get all the name strings that are in both arr1 and arr2 by calling arr1.filter with a callback that returns the condition that the items are also included with arr2 with arr2.includes(n) .

Then we assign the returned result to result .

Therefore, result is [“sue”, “kathy”] .

Categories
JavaScript Answers

How to Use setTimeout Sequentially in JavaScript?

To use setTimeout sequentially in JavaScript, we can create a promise with a callback that calls setTimeout and use it multiple times.

For instance, we can write:

const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}

(async () => {
  await sleep(100)
  await sleep(200)
})()

We create the sleep function that returns a promise we create with the Promise constructor.

The callback use resolve as the callback for setTimeout .

ms is the number of milliseconds to delay the call of resolve .

Then we create an async function that calls sleep with 100 and 200 milliseconds and call it immediately.

Categories
JavaScript Answers

How to Get the Entered Value From a TinyMCE Text Area?

To get the entered value from a TinyMCE text area, we can use the tinyMCE.activeEditor.getContent() method.

For instance, if we have the following HTML:

<script src="https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>

<form method="post">
  <textarea id="mytextarea">Hello, World!</textarea>
</form>

to add the TinyMCE script and text area, then we can get the value when the editor is initialized by writing:

tinymce.init({
  selector: '#mytextarea',
  setup(editor) {
    editor.on('init', () => {
      console.log(tinyMCE.activeEditor.getContent())
    })
  }
});

We call tinymce.init to create the text editor.

selector is the textarea element that we want to convert to a TinyMCE editor.

Then we have the setup method that calls editor.on with 'init' to watch when the editor is initialized.

Then callback will run when it’s initialized, so we can get the input value of the editor when the editor is initialized with tinyMCE.activeEditor.getContent() .

Therefore, we should see '<p>Hello, World!</p>’ logged.

Categories
JavaScript Answers

How to Print All Methods in a JavaScript Object?

To print all methods in a JavaScript object, we can use the Object.keys method to get all the top-level property keys of the JavaScript object in an array.

Then we call the filter method to filter out the keys for values that aren’t methods with the typeof operator.

Then we map the method keys to methods with map .

For instance, we can write:

const getMethods = (obj) => {
  return Object.keys(obj)
    .filter((key) => typeof obj[key] === 'function')
    .map((key) => obj[key]);
}

const obj = {
  foo() {},
  bar: 1
}
console.log(getMethods(obj))

We have the getMethods function that takes an obj object.

Then we call Object.keys with obj to get the top-level string property keys.

Then we call filter with a function that returns the properties that are functions with the typeof operator.

Next, we call map to map each key to their corresponding value.

Therefore, if we call getMethods with obj , we get the foo method in the array.

Categories
JavaScript Answers

How to Use the Mutation Observer for Watching the Creation of New Elements?

To use the mutation observer for watching the creation of new elements, we can use the MutationObserver constructor to watch the element that contains the element that will be added.

For instance, if we have the following HTML:

<div id='foo'>
  click me
</div>

and we want to watch for an element with ID bar to be added, then we can write:

const foo = document.querySelector('#foo')
foo.addEventListener('click', () => {
  const bar = document.createElement('div')
  bar.id = 'bar'
  foo.appendChild(bar)
})

const obs = new MutationObserver((mutations, observer) => {
  for (const m of mutations) {
    for (const n of m.addedNodes) {
      if (n.id === "bar") {
        console.log("bar was added!");
      }
    }
  }
});

obs.observe(foo, {
  childList: true
});

We select the div with document.querySelector .

Then we call foo.addEventListener to add a click listener to the foo element.

In the click listener callback, we call document.createElement to create a div and append it into the div with ID foo with appendChild .

bar.id is set to 'bar' so the new div’s ID is bar .

Next, we create a new MutationObserver instance with a callback that loops through all the mutations and in it, we loop through all the nodes that are added, which are stored in m.addedNodes .

Inside the inner loop, we check for an element that’s added with ID bar .

If it’s true , then we log 'bar was added!' .

Therefore, when we click on the foo div, we’ll see the message logged.