Compare values in two arrays using Iterator in Javascript? - javascript

I know how to compare values in two arrays using 2 for loops however I was looking for something a bit more sophisticated like creating an iterator to iterate through one of the arrays and passing the other array to mapmethod . Is that even possible?
I'm doing a small program for class which takes an array and x arguments and I currently have extracted the values from the arguments.
function dest(arr){
var args =[];
for(var i = 1; i < arguments.length; i++){
args.push(arguments[i]);
}
return args;
}
console.log(dest([1, 2, 3, 4], 4, 4));
Now, how could I do the iterator part to compare the values inside arr and args? Thanks for the help.
The result should be the results that match from both arr and args.

You can use the built in filter method
var arr = [2, 3, 4, 5, 6];
var args = [3, 5, 6, 7];
var result = arr.filter(function(element) {
return args.indexOf(element) > -1;
});
This will filter out all the elements out that are not present in both arrays. The result is a new array that contains only the matching values [3, 5, 6].

Related

map() method mutating the calling Array

map() can't mutate the calling array, instead it returns a new Array with modified values.
But, the following code mutating the original Array, is there any wrong in my understanding?
const arr = [1, 2, 3, 4, 5];
arr.map((num, index, arr1) => {
return arr1[index] = num * 2;
});
console.log(arr); // [2, 4, 6, 8, 10]
Well, you're mutating the original array by passing its reference into the callback function inside map() (arr1) and then manually accessing the indices. It will create a new array if you just return the value from that function.
const arr = [1, 2, 3, 4, 5];
const arr1 = arr.map((num) => {
return num * 2;
});
console.log(arr); // [1, 2, 3, 4, 5]
console.log(arr1); // [2, 4, 6, 8, 10]
The third argument to the callback function of map is the
original/source array on which the map is called upon
The arr and arr1 are both same i.e both are referencing on the same array, You can see it by using console.log(arr === arr1). So what ever you operation perform on the arr1, it gonna affect the arr.
const arr = [1, 2, 3, 4, 5];
arr.map((num, index, arr1) => {
console.log(arr1 === arr);
return num * 2;
});
You can just return num * 2 from the callback function. map internally creates a new array and return it. So you don't have to assign it as
arr1[index] = num * 2
You can also make it one-liner as:
arr.map((num, index, arr1) => num * 2)
const arr = [1, 2, 3, 4, 5];
const result = arr.map((num, index, arr1) => {
return num * 2;
});
console.log(arr); // [2, 4, 6, 8, 10]
console.log(result); // [2, 4, 6, 8, 10]
Array.map creates a new array populated with the results of calling a provided function on every element in the calling array.
Here its specifed that you must call or execute a function on every element of calling array.
What is the issue with your code?
You are not actually calling a function, you are instead updating the original array. If you are looking to create a new array by multiplying each node of the element with 2, you should do something like below.
Working Example
const arr = [1, 2, 3, 4, 5];
const newArray = arr.map((nodeFromOriginalArray, indexOfCurrentElement, arrayFromMapCalled) => {
return nodeFromOriginalArray * 2;
});
console.log(arr);
console.log(newArray);
Lets debug the paremeters inside the map function.
Here we have provided three arguments.
First argument nodeFromOriginalArray: The current element being processed in the array. This will be each node from your calling array.
Second argument indexOfCurrentElement: The index of the current element being processed in the array. Which means, the index of current element in calling array.
Third argument arrayFromMapCalled: The array map was called upon. This is the array on which the map function is getting executed. Please note, this is the original array. Updating properties inside this array results in updating your calling array. This is what happened in your case.
You should not modify your original array, which is the third parameter. Instead, you should return your node multipled by 2 inside map and assign this to a new array. Updating the third paramater inside the map function will mutate your calling array.
When calling map on an array, you provide a mapper with three arguments, an item in the array, it's index and the array itself (as you've represented in your snippet).
map takes the value returned by the function mapper as the element at the index in a new array returned by the operation.
const arr = [1,2,3,4,5]
const doubled = arr.map(x => x * 2) // [2,4,6,8, 10]
A over simplified implementation of map (without the index and originalArray params) might look like this. Let's assume that instead of being a method on the array instance, it's a function that takes an array and a mapper function.
I would not recommend re-implementing in production code, there's the native implementation as well as several libraries such as lodash and underscore that implement it.
function map(arr, mapper) {
const result = [];
for (const item of arr) {
const resultItem = mapper(item);
result.push(resultItem);
}
return result;
}
function double(x) {
return x * 2;
}
const doubled = map([1,2,3,4,5,6], double); // [2, 4, 6, 8 ,10, 12]

Return an array with all the elements of the passed in array but the last

Instructions:
Write a function called getAllElementsButLast.
Given an array, getAllElementsButLast returns an array with all the elements but the last.
Below is my code that will not pass the requirements for the question. I am not sure why this is not correct even though I am getting back all the elements besides the last.
var arr = [1, 2, 3, 4]
function getAllElementsButLast(array) {
return arr.splice(0, arr.length - 1)
}
getAllElementsButLast(arr) // [1, 2, 3]
I think the reason why it's not accepted is because with splice() you change the input array. And that's not what you want. Instead use slice(). This method doesn't change the input array.
var arr = [1, 2, 3, 4]
function getAllElementsButLast(array) {
var newArr = array.slice(0, array.length - 1);
return newArr;
}
var r = getAllElementsButLast(arr);
console.log(r);
console.log(arr);

Choose if array element repeats itself twice -- Javascript [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 6 years ago.
There is a javascript array
var arr = [0, 1, 2, 2, 3, 3, 5];
I want to choose elements that repeats twice. In this case its 2 and 3. and i want attach them into a variable.
var a = 2, b = 3;
As far as i know there is no built-in function to do that job. How can i do that. Thanks.
You can use filter to get the values that occur twice.
var arr = [0, 1, 2, 2, 3, 3, 5];
var dups = arr.filter ( (v,i,a) => a.indexOf(v) < i );
console.log(dups);
In comments you stated you would only have doubles, but no values that occur more than twice. Note that the above would return a value more than once, if the latter would be the case.
This returns the values in an array, which is how you should work. To put them in separate values can be done as follows:
var [a, b, ...others] = dups;
...but you would have to know how many variables to reserve for that, and it does not make your further program any easier. JavaScript has many nice functions (methods) for arrays, so you should in fact leave them in an array.
There is no built in function to do that indeed.
You will have to loop thought the array and keeping track of the number of occurrences of the elements, while building a response array.
You could filter a sorted array.
var arr = [0, 1, 2, 2, 3, 3, 5],
repeats = arr.filter(function (a, i, aa) {
return aa[i - 1] === a;
});
console.log(repeats);
Most simple way to do this is the following:
var dups = [];
var arr = [0, 1, 2, 2, 3, 3, 5];
arr.forEach(function (v, i, a){
delete arr[i];
if (arr.indexOf(v) !== -1){
dups.push(v);
}
});
console.log(dups);
It's destructive however.

JQuery Remove array from array of arrays

So I have an array of 2-element arrays, and I'm wondering if any of you know how to remove an array given the two elements of an array.
For example, the array would contain the following elements:
[1, 3]
[2, 5]
[1, 1]
Given the two numbers 2 and 5 in that order, is there any way to remove the second array?
Search the array for a match by some method. You could try each comparing each list in the larger list to the list given to you, or create a list from the numbers given to you and pass that. Then compare item by item for each list until you match each item-for-item every one.
If you find it use that index and look into the splice method from the javascript library. For example my_lisy.splice(2,2) argument 1 refers to the index of the list, and argument two refers how many items to remove.
You can try something like this:
var arr = [[1, 3], [2, 5], [1, 1]];
var result = [];
for(var i = 0, len = arr.length; i < len; i++) {
// If the element is the one we don't wan't, skip it
if(arr[i][0] == 2 && arr[i][1] == 5) {
continue;
}
// Otherwise, add it to the result
result.push(arr[i]);
}
console.log(result); //[[1, 3], [1, 1]]
You can add or extract any logic from the loop to suit your needs

multidimensional arrays and function calls in javascript

I am trying to work with a multi-dimensional in the following way
function 2darray(mynum) {
var outarray[];
outarray.push(1, 3, 5);
outarray.push(2, 4, 6);
var inarray[];
for (var i = 0; i < outarray.length; i++) {
inarray.push(outarray[i]);
}
// now i want to pass info to another function
getmyarray(inarray[mynum])
}
function getmyarray(access) {
// and access the passed values here, but am i doing the following correctly, and what do i put where the ?'s are..
xassess = access[ ? ][0];
yassess = access[ ? ][1];
}
There are no multi dimensional arrays in Javascript, so what you have is an array of arrays, also known as a jagged array.
Just omit the second index, and you will send the inner array to the function:
getmyarray(inarray[mynum]);
In the function you have a plain array of numbers, so just access it by a single index:
xassess = access[0];
yassess = access[1];
There are no traditional multidimensional arrays in javascript, only arrays of arrays.
// a literal array
var my2dArray = [
[1, 2, 3],
[4, 5, 6]
];
// a "constructed" array
var my2dArray = [];
my2dArray.push([1, 2, 3]);
my2dArray[1] = [4, 5, 6];
my2dArray[2] = [];
my2dArray[2][0] = 7;
Accessing a 2D array is pretty plainforward too; it just works like a 1D array returning another array.
my2dArray[0] == [1, 2, 3];
my2dArray[0][0] == 1;
my2dArray[0][1] == 2;
my2dArray[1][2] == 6;
thanks bart!!
var my2dArray =[
[1, 2, 3],
[4, 5, 6]
];
works great! and when i pass it into a function
getmyarray(my2darray[mynum])
i can access like you would expect!
function getmyarray(mypassedarray)
{ var x=mypassedarray[0];
and console.log(x); is correct!
..now i'm not sure why,but when i try to use the passed values in the google earth plug-in i get
"error: error calling method on npobject" and that error comes on the range part...investigation in progress..

Categories

Resources