I have the following structure, either a single string array ['stufff sjktasjtjser ((matchthis))'], or the same structure in a nested array ['stufff', ['more stuff ((matchhere))'], '((andanother))'];
I can loop and match all regex in the brackets and even replace the text:
//after flattening the array lets take the first one, assume I am looping in the first element.
var matches = currentArrayElement.matchAll('fancyregex') //pretend I am matching the brackets
matchs.forEach(match=>currentArrayElement=currentArrayElement.replaceAll(match[0],'whatwhat'))
console.log(currentArrayElement)//'stufff sjktasjtjser whatwhat'
//but what I actually want is
// currentArrayElement = ['stufff sjktasjtjser','whatwhat'];
Does anyone knows how I can achieve that? Or any template lib that can do that within nested arrays? I need to output sometimes an array of a string ['tss'] and sometimes an array with an object [{}].
Thanks.
The issue was that I needed to change the array in that index not the entire array.
Here is what I did then:
//after flattening the array lets take the first one, assume I am looping in the first element.
var matches = currentArrayElement.matchAll('fancyregex') //pretend I am matching the brackets
matches.forEach((match) => {
currentArrayElement[i] = c.split(match[0]).flatMap(
(value, index, array) => (array.length - 1 !== index
? [value, 'whatwhat',]
: value),
);
});
Related
Currently I iterate through a set of linkedObjects to to search for an isMatch. This test looks to see if element.id is present in the array obj.resource_ids if it is then we add the printable-string from the matching appointmentObj to an array in printStr.
The problem comes because value.resource_uniqueids could be an array containing many ids but my test only ever finds one.
Somehow I need to match all the ids in value.resource_uniqueids. - It might be the case that I need to add a new appointmentObj for each value.resource_uniqueids and then concatenate each equivalent printable-string
I hope this makes sense. How do I add a new ${currentMatch.printable-string} for each match of value.resource_uniqueids
Thanks !
_.forEach(appointmentObj, (value,i) => {
// value.resource_uniqueids is always an array, most of the time it only has one element
// but sometimes it can have more than one which means we only match one below in isMatch function
_.set(appointmentObj[i], 'resource_ids', value.resource_uniqueids );
_.set(appointmentObj[i], 'printable-string', `${value.title}, ${moment(value.created_at).format( 'Do MMMM YYYY')}` );
});
linkedObjects.forEach((element, index) => {
let isMatch = appointmentObj.find((obj) => {
return _.includes(obj.resource_ids,element.id);
});
if(isMatch) {
linkedObjects[index]['content']['printstring'] = `${currentMatch.printable-string}`;
}
});
The problem comes because value.resource_uniqueids could be an array
containing many ids but my test only ever finds one.
Array.prototype.find() returns a single matched element from within an array. Use Array.prototype.filter() if expected result is more than one matched result from within the iterated array.
Suppose I have an Javascript array,
var example = [and, there,sharma<br, />, ok, grt]
Now I want to randomly delete some array values - but not those values which have
<br
in them, in the above example, I want to make sure
"sharma<br" is not deleted.
I also do not want to delete "/>".
Can anyone help me. I would really appreciate the answer.
First of all, that is not a valid array, unless you are missing the string quotes. Anyway, what you are searching for is Array.Filter. In your case :
var filtered = example.filter(v => v.indexOf("<br") != -1 || v.indexOf("/>") != -1)
If I have understood the problem correctly, then you want to keep those entries in the array which have substrings "<br" and "/>"
If thats the case, you can try using javascript string method includes() to see if a string contains a particular substring.
JavaScript array must be created as below
var example = ["and"," there"",sharma<br","/>","ok"," grt"];
Using splice method , to delete the array values specifying the index positions.
array splice() method changes the content of an array, adding new elements while removing old elements.
Syntax
Its syntax is as follows −
array.splice(index, howMany, [element1][, ..., elementN]);
Parameter Details
index −
Index at which to start changing the array.
howMany −
An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.
element1, ..., elementN −
The elements to add to the array. If you don't specify any elements, splice simply removes the elements from the array.
Return Value
Returns the extracted array based on the passed parameters.
var removed = arr.splice(2, 2);
This would remove your suggested output to be my assumption .
function getFileExtension(i) {
if (i.indexOf(".") < 0) {
return false;
}
var filenameParts = i.split(".");
return filenameParts[filenameParts.length-1];
}
Here's the whole code. I understand it all except for the last line. I know what it does, but I don't know how or why. The second to last line splits the string at the ".", and then how does the last line actually get all the letters on the right side of the string?
By calling var filenameParts = i.split("."); an array is created containing the different parts. Imagine we use the filename test.txt and we use that string to split, we'll get an array like so:
filenameParts = ["test", "txt"]
Because the index of the first item in an array is 0, and we need the last item in the array, we call filenameParts.length-1 to get to the last item.
More information about javascript arrays can be found here.
The .split() function returns an array of strings, not a string. The expression filenameParts[filenameParts - 1] fetches the last element of the array.
filenameParts.length delivers the count of the filenameparts, split in the line above. filenameParts[number] delivers the one item of the array, which is positioned at number. -1 because arrays start at 0 not at 1. So it delivers the last item of the array. Clear?
filenameParts is an array and you read a single value with it's index. A value in this case is one part of the string between the ".".
filenameParts.length is equal to the count of values inside the array. As an array index starts with 0 you have to subtract 1 to get the index of the last value.
It looks like your function getFileExtension is designed to return the file extension of a given file. For example getFileExtension('image.gif') would return gif.
In the line (given that i is set to image.gif):
var filenameParts = i.split(".");
filenameParts will be an array, where image.gif has been split on the period. So filenameParts = ['image', 'gif'] where element zero is image and element one is gif. Remember that array indices are zero-based!
In the last line:
return filenameParts[filenameParts.length-1];
the function itself will return the last element in the filenameParts array (['image', 'gif']) which is gif. The part filenameParts.length-1 says get the length of the filenameParts array (which is 2), subtract 1 (which is 1), and return that element of the filenameParts array. So we return filenameParts[1] which is the last element of the array (remember, array indices are zero-based).
To get the last element of the array we could also have done
return filenameParts.pop();
because the pop() function returns the last element of an array.
var filenameParts = i.split('.') returns an array of made of the splitted elements of i
filenameParts[filenameParts.length-1];
select the last element of that array
underscorejs - How to remove array?
I have an array of objects. I would like to remove an array. Please refer my code below for more details,
array = [{a:10,b:20},{c:10,b:20},{a:10,d:20}];
Expected output: {a:10,b:20},{c:10,b:20},{a:10,d:20}
As I understand You need output without []. To manage that first stringify array, next cut first and last letter.
var array = [{a:10,b:20},{c:10,b:20},{a:10,d:20}];
var str=JSON.stringify(array);
console.log(str.substring(1,str.length-1));
Final string has no [] signs but this is not valid JSON structure. In JSON must be one root element like [] or {}.
Here is the problem. How do I do this below. The array within an array is throwing me off.
[...] alert to the screen the entire first movie in eightiesMovies, but only using the eightiesMovies variable. For now, use the concatenation operator to unite the words into one string. Remember to be attentive to necessary whitespace [...]
var movie1 = [ 16, "Candles"];
var movie2 = [ 3, "Men", "and", "a", "Baby"];
var eightiesMovies = [ movie1, movie2];
I have tried these answers to no avail
alert(eightiesMovies[0][0].concat("", eightiesMovies[0][1]));
alert(eightiesMovies([0][0]).concat("", eightiesMovies([0][1]));
Very simple:
movie1.concat(movie2) // will combine the 2 arrays
movie2.join(''); will join the element in the array
result:
movie2.join('') => "3MenandaBaby"
eightiesMovies[0][0] + " " + eightiesMovies[0][1]
The concatenation operator in this case is +, which is used to concatenate strings together. Since this is a nested array, you can chain array access. You want the first movie (which is an array in the first element of the eightiesMovies array at position 0). Then just concatenate each value of that array. You would have to know the length of the arrays ahead of time. That is to say the above would only print out part of the second movie.