'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
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 1:[1]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
