Categories
JavaScript Answers

How to convert the arguments object to an array in JavaScript?

To convert the arguments object to an array in JavaScript, we should replace it with the rest operator.

For instance, we write

const sortArgs = (...args) => {
  return args.sort((a, b) => {
    return a - b;
  });
};

to define the sortArgs function.

We use the spread operator to convert the arguments into an array with the ... rest operator.

args then has all the arguments we called sortArgs with.

And then we call args.sort to sort the arguments and returned a new array with the sorted values.

Categories
JavaScript Answers

How to get character array from a string with JavaScript?

To get character array from a string with JavaScript, we use the spread operator.

For instance, we write

const arr = [...str];

to spread the str string into a character array with the spread operator.

Categories
TypeScript Answers

How to check whether an array contains a string in TypeScript?

To check whether an array contains a string in TypeScript, we call the includes method.

For instance, we write

console.log(channelArray.includes("three"));

to check if the channelArray has 'three' in it with includes.

Categories
JavaScript Answers

How to get the index of the object inside an array, matching a condition with JavaScript?

To get the index of the object inside an array, matching a condition with JavaScript, we use the findIndex method.

For instance, we write

const a = [
  { prop1: "abc", prop2: "foo" },
  { prop1: "def", prop2: "bar" },
  { prop1: "ghi", prop2: "baz" },
];

const index = a.findIndex((x) => x.prop2 === "bar");
console.log(index);

to call findIndex with a callback that checks if the prop2 property of any object in a equals to 'bar'.

If the callback returns true, then the first index of the object with the condition true is returned.

Categories
JavaScript Answers

How to convert object array to hash map, indexed by an attribute value of the object with JavaScript?

To convert object array to hash map, indexed by an attribute value of the object with JavaScript, we use the Object.entries and Object.fromEntries methods.

For instance, we write

const array = [
  { key: "a", value: "b", redundant: "aaa" },
  { key: "x", value: "y", redundant: "zzz" },
];

const hash = Object.fromEntries(array.map((e) => [e.key, e.value]));

console.log(hash);

to call array.map to map the entries to an array of key-value pair arrays with the callback.

Then we call Object.fromEntries to convert the array to an object with the key as the property key and the values as the property values.