I have an array that looks like this:
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
I want to return the results like this:
'Rock Paper','Shoot','Dulce','Once','Apple Mic','Chairs'
This is what I have done so far:
includes = tagsI.map(tag => `'${tag}'`).join(',')
But this only separates by commas and single quotes the values.. not the values of the values as well.
How can I do this?
Thank you
Join the items of the array to a single string with commas. Split the string by the comma separators, map the items to the required format, and join again with commas.
const array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
const result = array
.join(',')
.split(',')
.map(tag => `'${tag}'`)
.join(',');
console.log(result);
split tag by comma and use another map
var tagsI = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
var result = tagsI.map(tag => tag.split(',').map(tag => `'${tag}'`)).join(',');
console.log(result)
How about using reduce :
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"];
//V1 : compatible with all browsers
var result = array.reduce((acc, elem, index, arr)=>{
var n_arr = elem.split(",").map(map_elem=> `'${map_elem}'`);
n_arr.forEach(fe_elem => acc.push(fe_elem));
return acc;
}, []).join(",");
console.log(result);
document.querySelector("#res1").innerHTML = result;
//V2: compatible with some browsers
var result2 = array.reduce((acc, elem, index, arr)=>{
var n_arr = elem.split(",").map(map_elem=>`'${map_elem}'`);
acc.push(...n_arr);
return acc;
}, []).join(",");
console.log(result2)
document.querySelector("#res2").innerHTML = result2;
<body>
<p id="res1"></p>
<p id="res2"></p>
</body>
The principle is the following :
We have an initial Array "array" in which we stored strings (["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"])
For each string in the array:
We split in an array the said string by ","
We surround each element of this array by quotes
We add each of these elements to the array that will be used as the result variable
We created a string joining by ","
PS: If you want an array instead of a string, just remove the join(",")
You'll first need to split each element in the array.
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"];
var split = array.map(v => v.split(","));
var flattened = [].concat.apply([], split);
var str = flattened.join(",");
Related
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 have an array that is filtered based on what the user types into a search box..
var x = ["Apple","Pear","Pineapple"];
var value = e.target.value;
var regex = new RegExp(`^${value}`, 'i');
var filtered = x.sort().filter(v => regex.test(v));
If I were to type "P" into the search box the console would print
["Pear","Pineapple"]
What I need however is another array of the original index position of Pear and Pineapple that would print the following
[1,2]
How would I go about achieving this?
You can do that in a single shot using reduce (read more about reduce here).
There is no need to filter, you can just generate another array, keep track of the index of the currently looped item (assuming you want the sorted index).
If you don't want the sorted index, just remove .sort. Not sure why it's there in the first place.
This solution requires a single iteration, which should be optimal (as long as you remove the unneeded sort).
var x = ["Apple","Pear","Pineapple"];
var value = 'P';
var regex = new RegExp(`^${value}`, 'i');
var filtered = x.sort().reduce((acc, next, i) => { // acc is the current accumulator (initially an empty array), next is looped item, i is item's index (what you want in the result).
return regex.test(next) && acc.push(i), acc // <-- if the regex test is successfull, `i` is pushed to the accumulator. In both cases (so, even if the regex fails) the accumulator is returned for the next iteration.
}, []); // <-- [] is the initial value of `acc`, which is a new empty array.
console.log(filtered);
Instead of filtering the array, filter the keys of the array instead:
var x = ["Apple","Pear","Pineapple"],
value ="P",
regex = new RegExp(`^${value}`, 'i'),
filtered = [...x.keys()].filter(i => regex.test(x[i]));
console.log(filtered)
keys() method returns a Array Iterator. So, you need to use spread syntax or Array.from() to convert it to an array
You could get first the value/index pairs, filter and get either the values or indices.
Intead of a RegExp, you could use String#startsWith, which has no problems of characters with special meanings.
var array = ["Apple", "Pear", "Pineapple"],
value = 'P',
filtered = array
.sort()
.map((v, i) => [v, i])
.filter(([v]) => v.startsWith(value)),
values = filtered.map(([v]) => v),
indices = filtered.map(([, i]) => i);
console.log(values);
console.log(indices);
You can get your indexes with indexOf() from the original array like so:
const x = ["Apple","Pear","Pineapple"];
var regex = new RegExp(`^P`, 'i');
const filtered = x.sort().filter(v => regex.test(v));
const filteredIndexes = filtered.map(v => x.indexOf(v));
console.log(filtered);
console.log(filteredIndexes);
You could also use reduce to do it all in one iteration like the so:
const x = ["Apple","Pear","Pineapple"];
var regex = new RegExp(`^P`, 'i');
const [filtered, filteredIndexes] = x.sort().reduce((acc, val, i) => {
// If the regex fits, add to the arrays
if(regex.test(val)) {
// Adding to the array via array spread operator
acc = [[...acc[0], val],[...acc[1], i]];
}
return acc;
}, [[],[]]); // Initial value of accumulator
console.log(filtered);
console.log(filteredIndexes);
There simple code:
var arr = [];
for(var i = 0; i < 10; i++){
arr.push("some string with iterating value "+i);
}
I wonder if there is a one-line solution in which I enter the string and the maximum value and get an array of generated lines.
Try this, if the input is 5, you can have it as N and get the input from user
DEMO
var result = Array.from(new Array(5),(val,index)=> "some string " + index );
console.log(result);
const newArray = [...Array(10)].map((_, i) => `some string with iterating value ${i}`)
console.log(newArray)
You can use a spread operator and create a new array of the length you require, loop (map) over it and return the string. This will create a new array of the length (10) with the string you want in it.
How about making it a reusable function? E.g.
// Replaces '{i}' with the index number
var generateStringArray = (length, string) => Array.from(new Array(length), (val, index) => string.replace('{i}', index))
console.log(generateStringArray(6, "some string {i}"));
I'm passing myself a string of results from php by ajax that I would like to put into a two dimensional array in JavaScript
The string looks like: value1^*value2^*value3^*value4***value1^*value2^*value3^*value4
I would like to split the values by '^*' into the first row of the dimensional array, then the next row would be after the '***'
Desired array:
var Text = [['value1', 'value2','value3','value4'],[value1','value2','value3','value4']];
You can use split() to split your string into an array of strings ( value1^*value2^*value3^*value4 and value1^*value2^*value3^*value4 ), after that you will need map() to creates a new arrays inside each array which we get before.
Example:
var str = "value1^*value2^*value3^*value4***value1^*value2^*value3^*value4"
str = str.split('***')
str = str.map((value) => value.split('^*'))
console.log(str)
You can do something like that
var input = "value1^*value2^*value3^*value4***value5^*value6^*value7^*value8";
var res = input.split('***').map(function(rowValues){
return rowValues.split('^*');
})
console.log(res);