Categories
JavaScript Answers

How to Replace an Item in a JavaScript Array?

Sometimes, we may want to replace an item in a JavaScript array.

In this article, we’ll look at how to replace an item in a JavaScript array.

Array.prototype.indexOf and Assignment

We can use the JavaScript array’s indexOf method to find the index of a given value in an array.

Then we can use the index to assign the new value to that index.

For instance, we can write:

const arr = [523, 353, 334, 31, 412];
const index = arr.indexOf(353);
if (index !== -1) {
  arr[index] = 1010;
}
console.log(arr)

We call arr.indexOf with the value we’re looking for.

It’ll return the index of the first instance of a value if it exists or -1 otherwise.

So if index isn’t -1, then we can replace the value at the given index with a new one by assigning it as we did in the if block.

So arr is now:

[523, 1010, 334, 31, 412]

Array.prototype.map

We can use the map method to return a new array with the entries of the existing array mapped to new values.

To use this to replace one or more instance of a value, we can write:

const arr = [523, 353, 334, 31, 412];
const mapped = arr.map(a => a == 353 ? 1010 : a)
console.log(mapped)

We call map with a callback that checks if a , which is the value being iterated through is 353.

If it is, then we replace that with 1010.

Otherwise, we just return the existing value.

So mapped is now:

[523, 1010, 334, 31, 412]

Array.prototype.indexOf and Array.prototype.splice

We can also use the JavaScript array’s splice method to replace a value at the given index with a new one.

For instance, we can write:

const arr = [523, 353, 334, 31, 412];
const index = arr.indexOf(353);
if (index !== -1) {
  arr.splice(index, 1, 1010);
}
console.log(arr)

We get the index of 353 the same way.

But instead of assigning the value, we call splice with the index of the element to remove.

1 in the 2nd argument means we remove 1 element.

And the 3rd argument is the value we replace the item with.

So arr is the same as the first example.

Conclusion

We can use array methods to replace an object at the given index with another value.

Categories
JavaScript Answers

How to Get the Index of the Object Inside a JavaScript Array Matching a Given Condition?

Often times in our code, we want to get an object from a JavaScript array that matches the given condition.

In this article, we’ll look at how to find the index of the object that matches the given condition in a JavaScript array.

Array.prototype.findIndex

We can use the JavaScript array’s findIndex method to let us get the index of the object in an array that matches the given condition.

To use it, we write:

const arr = [{
    name: 'james'
  },
  {
    name: 'mary'
  },
  {
    name: 'jane'
  }
];

const index = arr.findIndex(x => x.name === "jane");
console.log(index);

We pass in the findIndex method with a callback that finds the item where the name property’s value is 'jane' .

Therefore, index should be 2.

Lodash findindex Method

If we’re using Lodash in our JavaScript project, we can also use its findIndex method to find the object that matches the given condition in an array.

For instance, we can write:

const arr = [{
    name: 'james'
  },
  {
    name: 'mary'
  },
  {
    name: 'jane'
  }
];

const index = _.findIndex(arr, x => x.name === "jane");
console.log(index);

to pass in the array to the 1st argument and the callback into the 2nd argument.

And we get the same result for index .

We can also pass in an object with the properties to search for.

To do this, we write:

const arr = [{
    name: 'james'
  },
  {
    name: 'mary'
  },
  {
    name: 'jane'
  }
];

const index = _.findIndex(arr, {
  name: 'jane'
});
console.log(index);

And we get the same result.

Array.prototype.map and Array.prototype.indexOf

Another way to find an object in an array that meets the given condition is to map the property values we’re looking for with the map method.

Then we can use indexOf to find the index of the given value assuming the property holds a primitive value.

For instance, we can write:

const arr = [{
    name: 'james'
  },
  {
    name: 'mary'
  },
  {
    name: 'jane'
  }
];

const index = arr.map(a => a.name).indexOf('jane')
console.log(index);

We call map to return an artay with all the name property values from each object.

Then we can call indexOf with what we’re looking for.

And so index should be the same as the other examples.

Conclusion

We can get the index of an object in a JavaScript array that meets the given property value with various array methods.

Categories
JavaScript Answers

How to Get a Character Array From a JavaScript String?

Sometimes, we want to get a character array from a string.

In this article, we’ll look at how to get a character array from a string.

String.prototype.split

A string instance’s split method lets us split a string by any separator.

If we want to get a character array from a string, we can use the split method with an empty string.

For instance, we can write:

const output = "Hello world!".split('');
console.log(output);

Then output is:

["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]

as a result.

Spread Operator

Another way to split a string into a character array is the spread operator.

We can do this since a string is an iterable object.

To use it, we write:

const output = [..."Hello world!"]
console.log(output);

Then we get the same value for output as before.

RegExp u flag

We can also use the string split method with a regex to split a string into a character array.

For instance, we can write:

const output = "Hello world!".split(/(?=[sS])/u);
console.log(output);

s matches any whitespace and S matches any non-whitespace character.

And the /u flag lets us do searches with Unicode strings properly.

?= is the followed by quantifier.

So we search for anything that follows a whitespace or non-whitespace character and split them.

And so we get the same result as before.

for-of Loop and Array.prototype.push

Since a string is an iterable object, we can for use the for-of loop to loop through each character.

For instance, we can write:

const output = [];
for (const s of "Hello world!") {
  output.push(s);
}
console.log(output);

s has the character from the string.

In the loop body, we call output.push to push character s into the output array.

So we get the same result as before.

Array.from

The Array.from method is a static array method that lets us convert an iterable object into an array.

So we can use it to convert a string into a character array.

For example, we can write:

const output = Array.from("Hello world!")
console.log(output);

And we get the same value for output as before.

Conclusion

There’re many ways to convert a JavaScript string into a character array.

This includes array methods, spread operator, and loops.

Categories
JavaScript Answers

How to Read a Local Text File with JavaScript?

Sometimes, we may want to read a text file stored on a user’s computer with JavaScript.

In this article, we’ll look at how to read a local text file stored on the user’s device with JavaScript.

Get File Content from File Input

We can read file content from a file selected with the file input into our web page.

For instance, we can write the following HTML:

<input type='file' accept='text/plain'>

to add the file input.

Setting accept to text/plain makes the file input only accept plain text files.

And we can add a change event listener to the file input by writing:

const fileInput = document.querySelector('input')
fileInput.addEventListener('change', (event) => {
  const input = event.target;
  const reader = new FileReader();
  reader.onload = () => {
    console.log(reader.result);
  };
  reader.readAsText(input.files[0]);
})

We call addEventListener to 'change' to add a change listener.

Then we get the input with event.target .

And we create a FileReader instance to let us read a file.

We set the onload listener to get the text read from a file with the reader.result property.

Then to read the file, we call reader.readAsText with the first selected file, which is stored in input.files[0] .

Also, we can substitute readAsText with readAsBinaryString to get the same result:

const fileInput = document.querySelector('input')
fileInput.addEventListener('change', (event) => {
  const input = event.target;
  const reader = new FileReader();
  reader.onload = () => {
    console.log(reader.result);
  };
  reader.readAsBinaryString(input.files[0]);
})

Read Text of a Selected File with the text Method

The object with the selected file has the text method to let us read the text from the file object directly.

It returns a promise with the text.

For instance, we can write:

const fileInput = document.querySelector('input')
fileInput.addEventListener('change', async (event) => {
  const text = await event.target.files[0].text()
  console.log(text)
})

to call the text method on the event.target.files[0] file object.

The text variable would then have the text we read from the selected file.

We keep using the file input HTML that we written before.

Conclusion

We can read a file from the FileReader instance or the text method of the selected file object.

Categories
JavaScript Answers

How to Parse a URL into the Hostname and Path in JavaScript?

Sometimes, we want to parse a URL into the hostname and path parts with JavaScript.

In this article, we’ll look at how to parse a URL into the hostname and path parts with JavaScript.

Create an a Element

We can create an a element and set the href property of it to the URL we want to parse,

Then we can get the properties of it to get the parts we want.

For instance, we can write:

const parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=foo#hash";

console.log(parser.protocol)
console.log(parser.host)
console.log(parser.hostname)
console.log(parser.port)
console.log(parser.pathname)
console.log(parser.hash)
console.log(parser.search)
console.log(parser.origin)

protocol has the protocol, which is 'http:' .

host is the hostname and the port, which is 'example.com:3000' .

hostname is the hostname, which is 'example.com' .

port is the port, which is 3000.

pathname has the pathname, which is the path after the host, which is '/pathname/' .

hash has the hash, which is #hash .

search has the query string with the question mark before it, which is '?search=foo' .

origin has the protocol and host together, which is ‘ http://example.com:3000’ .

URL Constructor

The URL constructor lets us parse the parts of a URL without creating an a element.

For instance, we can write:

const url= new URL("http://example.com:3000/pathname/?search=foo#hash")

console.log(url.protocol)
console.log(url.host)
console.log(url.hostname)
console.log(url.port)
console.log(url.pathname)
console.log(url.hash)
console.log(url.search)
console.log(url.origin)

We pass the URL into the URL constructor, and we get the same results as before.

The URL constructor is available with most modern browsers.

Conclusion

To parse a URL with JavaScript, we can create an a element and set its href property.

Or we can pass the URL into the URL constructor to get the same result.