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.
Related
I have two arrays one of it is having user id and another one is having user ids. Those arrays are as follows.
1)The array which is having user id.
data[key].effective_employees Which is eaqual to [2].
Now I have another array which is having numbers of employee ids which is as follows.
data2[0].id Which is eaqual to [2,22,21].
And now I am trying to see whether the array two has number in array 1 I am using the following logic to see whether it is working or not.
if ((/^\d+$/.test(_.intersection([data2[0].id.toString()], data[key].effective_employees)))) {
let isElem = _.contains(returnStackFilterd, value);
if (isElem == false) {
returnStackFilterd.push(value);
}
} else {
returnStackFilterd = _.without(returnStackFilterd, value);
}
But this is showing true for the number 2 if the array two is having 22. Psudo code of what is happening with it is as follows.
if([2]is in[22,21]){ it is printing true} I want false here as the number two is not in the second array. The second array contains 22 and 21 which is not eaqual to 2
How do i solve this problem? The above psudo code should print false.
Let's break down your test expression and see why it doesn't work.
First off, we know that data[key].effective_employees is [2]. data2[0].id might be [2, 22, 21] or [22, 21]. If I'm understanding your question correctly, you want the whole test expression to return true in the first case and false in the second case.
Rebuilding your test expression from the bottom up, the innermost expression we find is this:
data2[0].id.toString()
This is a string with the value '2,22,21' or '22,21', depending on which case we are talking about. Next, you wrap this string in an array:
[data2[0].id.toString()]
So now we have ['2,22,21'] or ['22,21']. Note the quotes; in either case, it is an array with a single element that is a string.
Next, you take the intersection of this array with data[key].effective_employees, which we know is [2]:
_.intersection([data2[0].id.toString()], data[key].effective_employees)
So this expression is effectively
_.intersection(['2,22,21'], [2])
or
_.intersection(['22,21'], [2])
You are always taking the intersection of two arrays, where the first contains a single string and the second contains a number. They can't have any elements in common, so that's always going to produce an empty array ([]).
Finally, you test whether that empty array matches a regular expression:
/^\d+$/.test(_.intersection([data2[0].id.toString()], data[key].effective_employees))
// is effectively the same as
/^\d+$/.test([])
Regular expressions are supposed to be matched against a string, not an array. JavaScript is very lenient in situations like these and will coerce the value you're passing to a string. That means that the value [] is first converted to the empty string '' before being matched to the regular expression /^\d+$/. The empty string does not contain any digits, so this test always returns false.
This is why your test doesn't work as intended. However, let's take a few steps back, because you seem to be doing many things you don't need to do. Why convert arrays to strings (and then back to array)? Why match against a regular expression, if you just want to know whether two arrays have elements in common?
The following, simpler expression will give you the elements that data[key].effective_employees and data2[0].id have in common:
_.intersection(data[key].effective_employees, data2[0].id)
This will evaluate to either [2] or [], depending on whether data[key].effective_employees contains the number 2 or not.
I suggest saving the result of this expression to a variable, because it makes your code easier to read. Let's call it commonIds:
const commonIds = _.intersection(data[key].effective_employees, data2[0].id)
Now you can formulate different conditions, based on what exactly you want this intersection to be like. My impression is that you just want it to be nonempty (i.e., at least one element in common). In that case, you can compare its length to zero:
if (commonIds.length > 0) {
// code for when there is an overlap
} else {
// code for when there is no overlap
}
As a final note, I recommend assigning your base expressions data[key].effective_employees and data2[0].id to variables as well. Again, this makes your code more readable, and it also ensures that you need to change only one line of code if those base expressions change. Putting it all together:
const key = 'x';
const data = { [key]: {
effective_employees: [2],
}};
const data2 = [{
id: [2, 22, 21],
}];
const userId = data[key].effective_employees;
const employeeIds = data2[0].id;
const commonIds = _.intersection(userId, employeeIds);
if (commonIds.length > 0) {
console.log('userId appears in employeeIds');
} else {
console.log('userId does not appear in employeeIds');
}
<script src="https://underscorejs.org/underscore-umd-min.js"></script>
If data[key].effective_employees is the number 2, and data2[0].id is the array [2, 22, 21], the expression to test whether data2[0].id contains data[key].effective_employees is:
data2[0].id.includes(data[key].effective_employees)
From your original question, data2[0].id.toString() coerces the array to a string 2,22,21, which is no use to you. You also do not need to use Underscore for this.
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),
);
});
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 {}.
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(' '));
Starting out with:
ArrayA = [ ["Element0"], ["Element1"], ["Element2"] ];
and
ArrayB = [];
After a for-loop:
ArrayB[i] = ArrayA.splice(x,1);
then
ArrayB = [ [["Element0"]], [["Element1"]], [["Element2"]] ]
Any clue WHY this is happening?
Array.splice returns an array of the removed items. In ArrayA, each item is an array, so Array.splice returns an array containing that array. For example,
ArrayA.splice(0, 1) returns [["Element0"]]. If you use a look to populate ArrayB like this, you'll end up with an array in which each element is an array containing a single array, which is what you have.
If you always use Array.splice for a single element and you want that element to be returned, you could write ArrayA.splice(0, 1)[0] to get the first element.
Also, do you really want ArrayA to be an array of arrays? Or do you want it to be an array of strings? If so, that would simply be ArrayA = ["Element0", "Element1", "Element2"]; and the result of ArrayA.splice(0, 1) would be "Element0".