Categories
JavaScript Answers

How to map an array with duplicate values to a unique array in JavaScript?

Sometimes, we want to map an array with duplicate values to a unique array in JavaScript.

In this article, we’ll look at how to map an array with duplicate values to a unique array in JavaScript.

How to map an array with duplicate values to a unique array in JavaScript?

To map an array with duplicate values to a unique array in JavaScript, we can use some array methods.

For instance, we write:

const data = [{
    "topicId": 1,
    "subTopicId": 1,
    "topicName": "a",
    "subTopicName1": "w"
  },
  {
    "topicId": 2,
    "subTopicId": 2,
    "topicName": "b",
    "subTopicName2": "x"
  },
  {
    "topicId": 3,
    "subTopicId": 3,
    "topicName": "c",
    "subTopicName3": "y"
  },
  {
    "topicId": 1,
    "subTopicId": 4,
    "topicName": "c",
    "subTopicName4": "z"
  }
];

const noDups = [...new Set(data.map(d => d.topicId))].map(topicId => {
  return data.find(d => d.topicId === topicId)
})
console.log(noDups)

We create a new set with the topicIds with the duplicates removed and spread that back to an array.

Then we call map with a callback to return the first item with the given topicId in data.

Therefore, noDups is:

[
  {
    "topicId": 1,
    "subTopicId": 1,
    "topicName": "a",
    "subTopicName1": "w"
  },
  {
    "topicId": 2,
    "subTopicId": 2,
    "topicName": "b",
    "subTopicName2": "x"
  },
  {
    "topicId": 3,
    "subTopicId": 3,
    "topicName": "c",
    "subTopicName3": "y"
  }
]

Conclusion

To map an array with duplicate values to a unique array in JavaScript, we can use some array methods.

Categories
JavaScript Answers

How to detect text change with Mutation Observer and JavaScript?

Sometimes, we want to detect text change with Mutation Observer and JavaScript?.

In this article, we’ll look at how to detect text change with Mutation Observer and JavaScript.

How to detect text change with Mutation Observer and JavaScript?

To detect text change with Mutation Observer and JavaScript, we can set the characterData option to true.

For instance, we write:

<div>

</div>

to add a div.

Then we write:

const mutate = (mutations) => {
  mutations.forEach((mutation) => {
    console.log(mutation);
  });
}

const target = document.querySelector('div')
const observer = new MutationObserver(mutate);
const config = {
  characterData: true,
  attributes: false,
  childList: true,
  subtree: false
};

observer.observe(target, config);

setTimeout(() => {
  target.textContent = 'hello world';
}, 1000);

We create a MutationObserver instance with the mutate function as the callback.

And we call observe with a config that has characterData set to true to observe text node changes.

Therefore, when we change the textContent of target to 'hello world', mutate would run.

Conclusion

To detect text change with Mutation Observer and JavaScript, we can set the characterData option to true.

Categories
JavaScript Answers

How to get child element from event.target with JavaScript?

Sometimes, we want to get child element from event.target with JavaScript.

In this article, we’ll look at how to get child element from event.target with JavaScript.

How to get child element from event.target with JavaScript?

To get child element from event.target with JavaScript, we can call querySelector on event.target.

For instance, we write:

<form>
  <div>
    <input />
  </div>
  <button type="submit">Submit</button>
</form>

to add a form with an input.

Then we write:

const form = document.querySelector('form')
form.onsubmit = (event) => {
  event.preventDefault()
  console.log(event.target.querySelector('input'));
}

to select the form with querySelector.

Next, we set form.onsubmit to a function that gets the input from the form with event.target.querySelector('input').

Since the submit event is triggered by the form, event.target is the form.

Conclusion

To get child element from event.target with JavaScript, we can call querySelector on event.target.

Categories
JavaScript Answers Vue Vue Answers

How to Set Up ESLint and Prettier in Vue.js Projects and Format Code Automatically with Prettier with VS Code?

Sometimes, we want to set up ESLint and Prettier in Vue.js projects and format code automatically with Prettier with VS Code.

In this article, we’ll look at how to set up ESLint and Prettier in Vue.js projects and format code automatically with Prettier with VS Code.

How to Set Up ESLint and Prettier in Vue.js Projects and Format Code Automatically with Prettier with VS Code?

To set up ESLint and Prettier in Vue.js projects and format code automatically with Prettier with VS Code, we install a few packages and VS Code extensions and change a few settings.

First, we install a few packages into our Vue project by running:

npm i -D babel-eslint eslint eslint-plugin-import eslint-plugin-node eslint-plugin-promise eslint-plugin-prettier

We install the ESLint with plugins for Vue projects.

Then we install extensions by pressing ctrl+shift+p in VS Code and search for ‘Extensions: Install Extension’.

Next, in the extensions search box on the left, we search for Prettier, ESLint, and Vetur and install them by clicking install.

After that, we press ctrl+shift+p in VS Code and search for ‘Preferences: Open Settings (JSON).

And then we paste the following into settings.json:

{
    "extensions.ignoreRecommendations": true,
    "[css]": {
        "editor.defaultFormatter": "sibiraj-s.vscode-scss-formatter"
    },
    "files.eol": "\n",
    "files.trimTrailingWhitespace": true,
    "editor.renderControlCharacters": false,
    "editor.renderWhitespace": "none",
    "javascript.updateImportsOnFileMove.enabled": "always",
    "[typescript]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
    },
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[jsonc]": {
        "editor.defaultFormatter": "vscode.json-language-features"
    },
    "[json]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[html]": {
        "editor.defaultFormatter": "vscode.html-language-features"
    },
    "[scss]": {
        "editor.defaultFormatter": "sibiraj-s.vscode-scss-formatter"
    },
    "typescript.updateImportsOnFileMove.enabled": "always",
    "html.format.wrapLineLength": 80,
    "files.insertFinalNewline": true,
    "html.format.endWithNewline": true,
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true,
        "source.fixAll.stylelint": true
    },
    "[vue]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "editor.tabSize": 2,
    "editor.defaultFormatter": "esbenp.prettier-vscode"
}

to enable auto formatting and linting of Vue projects.

Finally, we create an .eslintrc.js file in the Vue project’s root and add:

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: ["plugin:vue/essential", "eslint:recommended", "@vue/prettier"],
  parserOptions: {
    parser: "babel-eslint"
  },
  rules: {
    "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
    "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off"
  },
  overrides: [
    {
      files: [
        "**/__tests__/*.{j,t}s?(x)",
        "**/tests/unit/**/*.spec.{j,t}s?(x)"
      ],
      env: {
        jest: true
      }
    }
  ]
};

into the file to enable the extensions needed for auto linting and formatting.

Conclusion

To set up ESLint and Prettier in Vue.js projects and format code automatically with Prettier with VS Code, we install a few packages and VS Code extensions and change a few settings.

Categories
JavaScript Answers

How to select by object path with Lodash and JavaScript?

Sometimes, we want to select by object path with Lodash and JavaScript.

In this article, we’ll look at how to select by object path with Lodash and JavaScript.

How to select by object path with Lodash and JavaScript?

To select by object path with Lodash and JavaScript, we can use the get method.

For instance, we write:

const obj = {
  foo: 'bar',
  count: '3',
  counter: {
    count: '3',
  },
  baz: {
    test: "qux",
    tester: {
      name: "Ross"
    }
  }
};
const result = _.get(obj, 'baz.tester.name', 'defaultVal');
console.log(result)

We call get with the object we want to find the property value for, the path to the property value, and the default value returned when the property isn’t found respectively.

Therefore, result is 'Ross' since obj.baz.tester.name is 'Ross'.

Conclusion

To select by object path with Lodash and JavaScript, we can use the get method.