Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cut the first word out of an array of strings and store in a new variable

I am currently getting back an array like this:

['Alica Brereton,Marijuana,9.18,50',
  'William Kotai,ecstasy,19.12,20',
  'Joel Forro,heroin,91.16,5',
  'David Ernest,Methamphetamine,108.78,5',
  'David Ernest,cocaine,80,2',
  'Joel Forro,ecstasy,19.12,10',
  'Gabriella Hyde,Marijuana,9.18,10',
  'Gabriella Hyde,Methamphetamine,108.78,8',
  'Marijuana,9.18,10'
]

I want to cut the names at the start of each string and store in a new variable, so I would have something like this:

['Alica Brereton',
  'William Kotai',
  'Joel Forro',
  'David Ernest',
  'Joel Forro',
  'Gabriella Hyde'
]

i’m working of a text file here is my current

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

code: 
const fs = require("fs");
const data = fs.readFileSync("data.txt").toString();
const lines = data.split("\n");

let customerKeys = lines[0].replace("customer", "Total Price");
lines.shift();
console.log(customerKeys);
console.log(lines);

let array = lines.filter((str) => {
  return str !== "";
});
let arrNoSpaces = array;

console.log(arrNoSpaces);
arrNoSpaces[6].replace("Gabriella Hyde,", "");
var GabriellaExtra = arrNoSpaces[6].replace("Gabriella Hyde,", "");
console.log(GabriellaExtra);

arrNoSpaces.push(GabriellaExtra);
console.log(arrNoSpaces);
arrNoSpaces.splice(-3, 1);

console.log(arrNoSpaces);

>Solution :

A regular expression can match letters and spaces (not commas) from each string, mapping to a new array.

const arr = ['Alica Brereton,Marijuana,9.18,50',
  'William Kotai,ecstasy,19.12,20',
  'Joel Forro,heroin,91.16,5',
  'David Ernest,Methamphetamine,108.78,5',
  'David Ernest,cocaine,80,2',
  'Joel Forro,ecstasy,19.12,10',
  'Gabriella Hyde,Marijuana,9.18,10',
  'Gabriella Hyde,Methamphetamine,108.78,8',
  'Marijuana,9.18,10'
];

const result = arr
  .map(line => line.match(/\w+ \w+/)?.[0]) // extract matches
  .filter((item, i, arr) => item && arr[i - 1] !== item) // filter out failed matches and dupes
console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading