Categories
JavaScript Answers

How to remove leading comma from a string with JavaScript?

To remove leading comma from a string with JavaScript, we call the substring method.

For instance, we write

const myOriginalString = ",'first string','more','even more'";
const myString = myOriginalString.substring(1);

to call myOriginalString.substring with 1 to return a substring of myOriginalString without the first character.

Categories
JavaScript Answers

How to remove an element from a list, with JavaScript Lodash?

To remove an element from a list, with JavaScript Lodash, we use the remove method.

For instance, we write

_.remove(subTopics, (currentObject) => {
  return currentObject.subTopicId === stToDelete;
});

to call remove to remove the item in the subTopics array that has the subTopicID equals stToDelete by calling it with the callback that returns the condition.

Categories
JavaScript Answers

How to check if item is in array in JavaScript?

To check if item is in array in JavaScript, we use the indexOf method.

For instance, we write

const blockedTile = ["118", "67", "190", "43", "135", "520"];

if (blockedTile.indexOf("118") !== -1) {
  // ...
}

to call blockedFile.indexOf with the item we’re looking for to see it’s in the blockedFile array.

It returns the index of the item if it exists and -1 otherwise.

If it returns something bigger than -1, then the item is found.

Categories
JavaScript Answers

How to transform object to array with JavaScript Lodash?

To transform object to array with JavaScript Lodash, we call the values method.

For instance, we write

const arr = _.values(obj);

to call values with obj to return an array with the property values in the obj object.

Categories
JavaScript Answers

How to zip two arrays in JavaScript?

To zip two arrays in JavaScript, we use the map method.

For instance, we write

const a = [1, 2, 3];
const b = ["a", "b", "c"];

const c = a.map((e, i) => {
  return [e, b[i]];
});

console.log(c);

to call a.map with a callback that returns an array with arrays of items in a and the items in b at the same position as the item in a.