Subscribe

Learn how to convert a list into an array in JavaScript

โœ๏ธ

Converting a excel list into an array in JavaScript

26 Aug, 2020 ยท 2 min read

๐Ÿšจ Real-world use-case: I wanted to convert an excel list into an array; it had 200+ records, so a pain to do manually.

So why not create something easy in JavaScript!

The end goal is to have a text area where we can input our list and auto-convert it into an array.

This is going to be the result in Codepen:

See the Pen Learn how to convert a list into an array in JavaScript by Chris Bongers (@rebelchris) on CodePen.

HTML Structure

The HTML will be super easy for this. We just need a textarea and a paragraph to output our array.

<div class="container">
  <textarea id="textarea">
Paste
your 
list 
here</textarea
  >
  <p id="array">["Paste","your ","list ","here"]</p>
</div>

CSS Styling

Let's also add some super easy CSS to make it look good:

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  flex-direction: column;
  background: #3a86ff;
}
textarea {
  padding: 10px;
  min-width: 200px;
  width: 50vw;
  height: 100px;
  margin-bottom: 10px;
  border-radius: 10px;
}
#array {
  background: #efefef;
  border: 1px dashed #333;
  padding: 10px;
  width: 50vw;
  min-width: 200px;
  word-wrap: break-word;
  margin-bottom: 10px;
  color: #ff006e;
  border-radius: 10px;
}

JavaScript convert a list into an array

Ok, on to the magic part, let's convert our array input into an array.

We start by adding defining our variables.

const textarea = document.getElementById('textarea');
const array = document.getElementById('array');

Now we can add our input listener to the textarea element.

textarea.addEventListener('input', function () {
  const arrayValues = textarea.value.split(/\n/g);
  array.innerHTML = JSON.stringify(arrayValues);
});

And then, for some magic, we will add a click event to our paragraph, which will auto-select all text.

array.addEventListener('click', function () {
  const range = document.createRange();
  const selection = window.getSelection();
  range.selectNodeContents(array);
  selection.removeAllRanges();
  selection.addRange(range);
});

An awesome, simple tool, but effective!

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API

Join 1829 devs and subscribe to my newsletter