underscorejs - How to remove array? - javascript

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 {}.

Related

Taking a string and diving it into a array given an regex

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),
);
});

Iterating the keys from a javascript hashmap gives empty string for last element

I need the keys from a javascript/typescript hash map in an array. I use the Map.Keys() method, and iterate the keys to populate the an array called:searchTerms. For some reason, the last value in the array is always an empty string.
When I view the hashMap in the debugger, I see exactly what I expect; keys of type string, and values of an array of strings, with no empty keys.
public setSearchTerms(searchMap: Map<string, Array<string>>) {
if(searchMap && searchMap.size) {
let myKeys = myMap.keys();
this.searchTerms = [...myKeys];
/*
for(let k of myKeys) {
if(k.length > 0) {
this.searchTerms.push(k);
}
}
*/
}
}
When I run the code as is, the searchTerms Array has all the keys from the map, plus an empty string. Using the for-of loop (Currently comment out) also puts in the empty string, but I put in the length check which resolve the issue. I just want to understand where the empty string comes from. I can make it work, but it's bugging me that I can't figure out where the empty string comes from.
Looks like it IS an cr/lf issue. Did a hexdump of the source file and there is an extra 0a0d at the end. Found a previous stack post that explained it. Thanks for pointing in the right direction.
Link

Javascript - Reduce array of arrays

Array input: [["test","test"],["test2","test"],["test2","test2"],["test","test2"]]
Array output: ["test test","test2 test","test2 test2","test test2"]
I'm able to obtain this output with:
output = input.join("|").replace(/,/g," ").toString().split("|")
However, I don't really like this workaround because:
It seems unnatural
If one of the arrays contains a comma itself, it will be also
removed
If one of the arrays contains a pipe itself, the split will be not as expected
How can I get the output without those handicaps?
Instead of joining the outer array, you can use map to join each inner array separately:
var arr = [["test","test"],["test2","test"],["test2","test2"],["test","test2"]];
var output = arr.map(subarr => subarr.join(' '));

How can I completely remove an object from an array in Javascript?

I have been using the following code:
formData.objectiveDetails.push(emptyObjectiveDetail);
This pushes a new emptyObjectiveDetail object onto the end of an array called objectiveDetails.
If for example the array of objectiveDetails contains 13 objects then how could I remove the one at position 5? I assume I could make this null but what I want to do is to completely remove it so the length of the array becomes 12.
This might be off topic but I have been considering adding underscore.js. Is this something that could be done with underscore?
formData.objectiveDetails.splice(5, 1)
First argument is the array index and the second the number of items to remove starting from that index.
You can use Splice to remove the object from the array. Something like this:-
formData.objectiveDetails.splice(5, 1)
Using underscore.js
objectiveDetails = _.without(objectiveDetails, _.findWhere(arr, {id: 5}));

Converting an array to a string in Javascript

I have a multi-dimensional array like this:
1 2 3
4 5 6
Now I need to convert this array into a string like 1,2,3;4,5,6.
Can any one suggest how to do this, please?
simply use the join method on the array.
> [[1,2,3],[4,5,6]].join(';')
'1,2,3;4,5,6'
It's lucky that you simply don't have to consider how the apply the join method on the inner lists, because a list is joined by comma by default. when a list is coerced into a string, it by default uses commas to separate the items.
As it was already mentioned by qiao, join() is not recursive.
But if you handle the recursion yourself you should acquire the desired result, although in a rather inelegant way.
var array = [[1,2,3],[5,6,7]];
var result = [];
array.forEach(
function(el){
result.push(
el.join(",")
);
});
result.join(";");
If you need to serialize an array into a string and then deserialize it later to get an array from the string you might want to take a look at JSON:
http://www.openjs.com/scripts/data/json_encode.php
Try this:
array.toString();
See here for reference: http://www.w3schools.com/jsref/jsref_tostring_array.asp
See answer by qiao for a much nicer approach to multidimensional arrays like this.

Categories