I fetched data from database so its coming in string format and I want to check this string with my array data
my string values come like
const input = "fish.jpg\nanimal.jpg\nfish.pdf\nanimal.pdf\nmammal_bio.pdf\nfish_bio.jpg\nfruit_bio.pdf"
I want to compare this data with my array which contain
check=["mammal_bio.pdf","animal_bio.pdf","fruit_bio.pdf","tree_bio.pdf"]
So i want to compare all the array values which contain _bio.pdf and store them as
matchedArray=["mammal_bio.pdf","fruit_bio.pdf"]
unmatchedArray=["animal_bio.pdf","tree_bio.pdf"]
You can get matched and unmatched using Array.filter and String.split:
const input = "fish.jpg\nanimal.jpg\nfish.pdf\nanimal.pdf\nmammal_bio.pdf\nfish_bio.jpg\nfruit_bio.pdf";
const check = ["mammal_bio.pdf","animal_bio.pdf","fruit_bio.pdf","tree_bio.pdf"];
const inputArray = input.split("\n");
const matchedArray = check.filter(e => inputArray.includes(e));
const unmatchedArray = check.filter(e => !matchedArray.includes(e));
console.log(inputArray);
console.log(matchedArray);
console.log(unmatchedArray);
const input ="fish.jpg\nanimal.jpg\nfish.pdf\nanimal.pdf\nmammal_bio.pdf\nfish_bio.jpg\nfruit_bio.pdf"
const checkArray=["mammal_bio.pdf","animal_bio.pdf","fruit_bio.pdf","tree_bio.pdf"]
const matchedArray=checkArray.filter((e)=>input.split('\n').indexOf(e)!== -1);
const unmatchedArray=checkArray.filter((e)=>input.split('\n').indexOf(e)=== -1)
console.log(matchedArray, unmatchedArray);
Please note that input has a separator \n between filename
You can easily achieve this result using reduce with a single loop over the check array.
const input =
"fish.jpg\nanimal.jpg\nfish.pdf\nanimal.pdf\nmammal_bio.pdf\nfish_bio.jpg\nfruit_bio.pdf";
const check = [
"mammal_bio.pdf",
"animal_bio.pdf",
"fruit_bio.pdf",
"tree_bio.pdf",
];
const inputArr = input.split("\n");
const result = check.reduce((acc, curr) => {
if (inputArr.includes(curr)) acc[0].push(curr);
else acc[1].push(curr);
return acc;
},[[], []]);
const [matchedArray, unmatchedArray] = result;
console.log(matchedArray);
console.log(unmatchedArray);
Related
I am struggling at the moment with making a new array of strings from another array that I have to filter for certain pattern.
Example:
let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654"
I guess this could be matched from this string as well. But my initial approach was to split this string at each / :
let splitArr = originalString.split('/');
// splitArr = ["4162416245", "OG74656489", "OG465477378", "NW4124124124", "NW41246654"]
Basically what I do have to achieve is to have 2 different array that is filtered down by pattern of the start of this strings. OG and NW is always fix won't change but numbers after I don't know.. Backend sends this data as OG(original ticket) NW(new ticket) so those prefixes are fix, I have to check for string starting with them and put them in they array:
ogArr = ["OG74656489", "OG465477378"]
nwArr = ["NW4124124124", "NW41246654"]
If you want 2 separate arrays, you can use filter and startsWith
let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654";
let splitArr = originalString.split('/');
const ogArr = splitArr.filter(s => s.startsWith("OG"));
const nwArr = splitArr.filter(s => s.startsWith("NW"));
console.log(ogArr);
console.log(nwArr);
Another option could be using reduce to travel the collection once, and pass in an object with 2 properties where you can extract the data from.
let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654";
let splitArr = originalString.split('/');
const res = splitArr.reduce((acc, curr) => {
if (curr.startsWith("OG")) acc.og.push(curr)
if (curr.startsWith("NW")) acc.nw.push(curr)
return acc;
}, {
"nw": [],
"og": []
})
console.log(res);
You can also use the Array.prototype.reduce() method to add the elements into an object containing all tickets.
This would lead to this results :
{
"OG": [
"OG74656489",
"OG465477378"
],
"NW": [
"NW4124124124",
"NW41246654"
]
}
let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654"
const tickets = originalString.split('/').reduce((acc, curr) => {
if(curr.startsWith('OG')) acc["OG"].push(curr)
else if(curr.startsWith('NW')) acc["NW"].push(curr)
return acc
}, {OG: [], NW: []})
console.log(tickets)
I would like some assistance to remove duplicates and remove the | and the '' at the start and end.
My code so far
const thedates = this.results
.filter((result) => result.thedate)
.map((item) => item.thedate)
.filter((thedate, i, arr) => arr.indexOf(thedate) === i);
// Split multiple thedates in strings and store in an array
let thedate = [];
thedates.forEach((item) => {
const splitArr = item.split(", ");
thedate = thedate.concat(splitArr).sort();
});
// Filter again for unique thedates
this.thedates = thedate.filter(
(thedate, i, arr) => arr.indexOf(thedate) === i
);
My output in the console from the code above
'full-time', 'full-time|full-time', 'full-time|full-time|full-time', 'full-time|full-time|full-time|full-time', 'full-time|full-time|part-time|full-time|part-time|part-time',
I would just like each entry to say: full-time, part-time or full-time if there is just one between the quotes.
Can anyone help to add to my code please?
You're essentially asking two things, how to turn a delimited string into array and how to remove duplicate values from an array. You can parse by using the .split() method, and remove duplicates from an array by constructing a set with it then turning it back into an array with the spread operator.
Altogether (where array is your input array):
let filteredArray = [ ...new Set( string.split( '|') ) ]
const string = "full-time|part-time|full-time|part-time|full-time|part-time|full-time|part-time|full-time|part-time|full-time|part-time|part-time|full-time|full-time|part-time|full-time|part-time|full-time|full-time|part-time|part-time";
let filteredArray = [ ...new Set( string.split( '|') ) ]
let result = filteredArray.join(', ');
console.log(result)
You could try something like this (similar to #Julien Mellon's post) where you use .split(), but you return an array of arrays with the second level array being the entry:
const thedates = ['full-time', 'full-time|part-time', 'full-time|part-time|full-time', 'full-time|full-time|part-time|full-time', 'full-time|full-time|part-time|full-time|part-time|part-time']
const theDatesFormatted = thedates.map(item => {
const arr = item.split('|')
const uniqueArr = [...new Set(arr)]
return uniqueArr
})
console.log(theDatesFormatted)
if your inputs are
'full-time', 'full-time|full-time', 'full-time|full-time|full-time', 'full-time|full-time|full-time|full-time', 'full-time|full-time|part-time|full-time|part-time|part-time'
perhaps you could just call .split('|') ?
I have an array of strings. Some of the strings within this array have a pipe character. I would like to split the strings by "|" and store all the unique values into a new array.
What would be an efficient way to get a temporary array with all the splited values in it, without using poor performance loops?
Once I have the temporary array with all the splited values in it, I plan de remove all duplicates like this :
var result = [...new Set(result)]
var arr = ["A|B|C","B|A","E|A|D","F"]
// result does not have to be sorted
var expectedResult = ["A","B","C","D","E","F"]
Use flatMap() and split() to get a single array, and use a Set to retain unique elements:
const array = ["A|B|C","B|A","E|A|D","F"];
const result = [...new Set(array.flatMap(v => v.split('|')))];
console.log(result);
.join('|') array as a string with pipes between all letters, then .split('|') by the pipe and then remove dupes with Set()
let data = ["A|B|C", "B|A", "E|A|D", "F"];
console.log([...new Set(data.join('|').split('|'))]);
I would go with
const result = arr.map(item => item.split("|")).flat();
const deduped = [...new Set(result)]
One more option:
const inputArray = ["A|B|C","B|A","E|A|D","F"];
const result = inputArray.reduce((acc, value) => acc.push(...value.split('|')) && acc, []);
console.log(result);
const splitSet = (arr) => {
const set = new Set();
for(const item of arr) {
const splited = item.split("|");
for(const piece of splited) {
set.add(piece);
}
}
return Array.from(set);
}
splitSet(arr); //result
The first thing that comes to my mind is this
const arr = ["A|B|C","B|A","E|A|D","F"];
const flatArr = arr.join('|').split('|');
const expectedResult = [...new Set(flatArr)];
I'm trying to convert a csv file row to an array, and then convert the numeric values from string.
This is my csv file row:
const row = "TEXT,2020-06-04 06:16:34.479 UTC,179,0.629323";
And this my goal array (last two numeric values without string format):
["TEXT","2020-06-04 06:16:34.479 UTC",179,0.629323]
I have tried in three differente modes, but I donĀ“t get the goal result.
Try 1:
const array1 = row.split(",");
Result:
["TEXT","2020-06-04 06:16:34.479 UTC","179","0.629323"]
Try 2:
const array2 = row.split(",");
for (let element in array3){
array3[element] = +array3[element];
}
Result:
[null,null,179,0.629323]
Try 3:
const array3 = row.split(",").map(x=>+x);
Result:
[null,null,179,0.629323]
Can someone help me?
Thanks!
Using isNaN()
const row = "TEXT,2020-06-04 06:16:34.479 UTC,179,0.629323";
const array = row.split(",").map(i => isNaN(i) ? i : +i)
console.log(array)
inNan Function in JS check wether number can be converted to Number.
Give it a try following method
const row = "TEXT,2020-06-04 06:16:34.479 UTC,179,0.629323";
const array1 = row.split(",");
const newArray = array1.map(value => toNumber(value))
console.log("newArray", newArray)
function toNumber(value) {
if(isNaN(value) || value === "")
return value
else
if(value.indexOf(".") === -1)
return parseInt(value)
else
return parseFloat(value)
}
One another way to accomplish this to multiple value by 1.
let array = row.split(",").map(value => isNaN(value) ? value : value * 1);
I need to turn a string formatted like that:
string = "John:31,Miranda:28"
Onto this;
obj = { "John" => 31, "Miranda" => 28 }
I did this :
const class = new Map();
array = string.split(",");
And obviously I do not know what do with it because after the split I get something like this:
["John:31", "Miranda:28"]
And I don't know how to turn it onto an object (using the ":" as a arrow)... Maybe I don't need to use the array as an intermediary? Any thoughts? Thanks
You can use split to split by comma, and then map on the resulting strings to split again by colon, and feed the resulting array of arrays into the Map constructor.
For instance, if you want the map keyed by the names, which I suspect you do:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => entry.split(":")));
console.log(map.get("John")); // "31" (a string)
If you want the numbers to be numbers, not strings, you'll need to convert them:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => {
const parts = entry.split(":");
parts[1] = +parts[1];
return parts;
}));
console.log(map.get("John")); // 31 (a number)
My answer here goes into some detail on your options for converting from string to number.
If you want the map keyed by value instead (which I suspect you don't, but...), you just have to reverse the order of the inner array entries:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => {
const [name, num] = entry.split(":");
return [num, name];
}));
console.log(map.get("31")); // John
So split on the commas, loop over it and split on the colon, and build the object.
var myString = "John:31,Miranda:28"
var myObj = myString.split(',').reduce(function (obj, part) {
var pieces = part.split(':')
obj[pieces[0]] = pieces[1]
return obj
}, {})
You could try something like this:
const data = "John:31,Miranda:28"
const splitData = data.split(',')
const result = splitData.reduce((newObject, item) => {
const [name, age] = item.split(':')
return {
...newObject,
[name]: parseInt(age)
}
}, {})
console.log(result)
I'll just add this here:
Basically, split string by the comma, then the colon.
Combine result into a map
const test = "John:31,Miranda:28";
console.log(test);
const obj = test.split(/,/).map(item => item.split(/:/));
console.log(obj);
const _map = new Map(obj);
console.log(_map);
console.log(_map.get("John"))