Becky Becky - 7 months ago 18
Javascript Question

Seperate matching value by hyphen

code:

var finArr = [];
data.forEach(function (line) {
if (line.toString().indexOf(text) !== -1){
finArr= finArr.concat(line);
//console.log( finArr)
}
})


console:

[
"59191", "TypeAV - Canada", "Available",
"422129", "TypeAA - Italy", "Available",
"959191", "TypeBB - USA", "N/A",
"6D968C", "TypeAV - Canada", "Available"
]


My question is, how do I remove the part after the hyphen (
-
) in each second value?

The expected result is

[
"59191", "TypeAV", "Available",
"422129", "TypeAA", "Available",
"959191", "TypeBB", "N/A",
"6D968C", "TypeAV", "Available"
]

Answer

Your best bet is to map over the nested arrays and return only the first element of a split on ' - '.

var finArr = [];
data.forEach(function (line) {
  finArr = finArr.concat(line.map(function (el) {
    return el.split(' - ')[0];
  }));
});

DEMO

You can also replace forEach with reduce.

var finArr = data.reduce(function (p, c) {
  return p.concat(c.map(function (el) {
    return el.split(' - ')[0];
  }));
}, []);

DEMO

Comments