I have two array of objects in javascripts. Like arr1[] = {emp1,emp2,emp3} where inturn emp1 has emp1.name and emp1.address as property.
Something like
arr1={object {name='a',address='b'} {name='c',address='d'} {name='e',address='f'} }.
arr2={object {name='a',address='b'}}.
I wanted to compare name property of two array objects and populate the missing items into another array. So result will be result[]={'c','e'}
Whats is the efficient way in achieving this? I don't expect code, please guide me in the right direction. Thanks.
The Array.filter method might be helpful. Check out more on it here.
the function could look like
function foo(arr1,arr2){
var arr3 = new Array();
var x=0;
for (var j =0; j<arr1.length; j++)
for(var i=0; i<arr2.length; i++)
if(arr1[j].name != arr2[i].name){
arr3[x]=arr1[i];
x++;
}
return(arr3);
}
This will loop through the 2 arrays and if the elements are not the same then they will be put in the third array. this is checking if any name in aarr1 is the same as in arr2. it doesn't check the other way.(ie if arr2 has an element that does not exist in arr1 it will not be put in arr3) but at least it should get you started.the function will accept the 2 arrays and return the third.
Related
I'm currently doing an assignment for school and could really use your help.
I have to declare a function which takes two arguments, x and an array, arr. It has to return an array which contains multiple arrays with x inserted into respectively index 0 in the first array, index 1 in the second array and so on until there's no more numbers in the array. See picture of an example and for clarification of what the final result is expected to look like. It has to work on any given array and the assignment specifies that slice() and concat() would be good to use. example of assignment
function insert_all_positions (x, arr) {
var newArr = [];
for(var i = 0; i < arr.length; i++) {
return(arr.concat(x)); }
};
This just adds the x-value to the end of the array and I have to loop it so the value will be inserted at all indexes. I'm thinking the array.splice() method can be used, I'm just not sure how as I'm not particularly experienced with it. Thank you :)
As Nina already said: the idea of assignments is, that you try something yourself which we can then help you to improve.
Nonetheless, here is one simple way of doing what was required:
function iap(v,arr){
var l=arr.length, ret=[];
for (var i=0;i<=l;i++) ret.push(arr.slice(0,i).concat([v],arr.slice(i,l)));
return ret;
}
console.log(iap(8,[1,2,3]));
Try this
function myFunc(x,arr){
let result =[]
for(let i=0;i<arr.length;i++){
let arrToAdd = [...arr]
arrToAdd[i]=x
result.push(arrToAdd)
}
return result
}
You create a result array that you push your arrays into, then you run a loop that will run the exact number of times as the length of your argument arr. Each iteration of the loop creates a new array that is a copy of arr and then you just change one number in it each time and add the entire array to the result.
I have an array of 11 objects which contain JSON data. I wrote a function in which a new key with a zero value is added to each of the objects. Now I want to update the value of the said key in all 11 objects. The data is stored in an array2 with 11 numbers. My for loop doesn't seem to work for this, and the only way to do it (so far) is to hard code it. Does anyone has a suggestion how this can be done?
The desired outcome would be this:
array[0].new_key = array2[0];
array[1].new_key = array2[1];
The first art of the function, before the for loop with j, is for adding the new key into the original array and that part works.
for (i = 0; i < array.length; i++) {
array.map(i => i.new_key = 0);
console.log(array)
for (j = 0; j < array2.length; j++) {
array[i].new_key = array2[j];
console.log(array)
}
}
}```
I split it into two functions, I realized that I made it too complicated and it didn't made sense. I wrote a second function that only updates all the key values, so indeed, I removed the inner loop as it was not needed. Thank you for the help.
.map() does not modify the original array:
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
You will want to get the result of the map by assigning it to a variable, and see what is happening there. Right now you don't do anything with it, so it will just disappear.
While the above is true for maps, in this case the original array is being modified as we access the object's properties and modify them there.
I have a problem with my JS function. For simplification, I want to fill an array (arr1) with n other arrays (arr2). In my loop I use a counter for the current postion in arr1 (cant use arr1.push for a reason). If I log all my arr2's in arr1 they are all the same, always the last one that was added. So I wrote a basic script to test it. I always log the first element and incement the counter.
I'm new to JS, is there some huge misunderstanding I don't get?
function test(){
var arr1 = [];
var arr2 = [];
var counter=1;
arr2[0]="first";
arr2[1]="first";
arr2[2]="first";
arr1[0]=arr2;
arr1[0].forEach(function(elem){console.log(elem);});
for (var i = 0; i < 10 ; i++) {
arr2[0]=counter;
arr2[1]=counter;
arr2[2]=counter;
arr1[counter]=arr2;
arr1[0].forEach(function(elem){console.log(elem);});
counter++;
}
}
<button onclick="test()">Click</button>
You can try to use the spread operator.
arr1[0]=[...arr2];
arr1[counter]=[...arr2];
An array is a reference type, so you always refer to the base, you don't put a copy of it inside of arr1 but a reference to the arr2.
You want a copy of arr2 to be assigned to arr1.
You can do this by creating a new Array, or more modern the ... spread operator
As Pointy said it, it just referenced the arr2 and doesn't create a copy.
So you need to
arr2=new Array();
at the beginning of the loop.
I have created an array and received another from a php file.
The data is fine but when i try to copy one array to another, it seems like when i change arr1 then arr2 is also changed.
It is being copied "by reference" and not "by value" as i need
I also tried slice() butit doesn't work, The variable does not being copied at all, not even "by reference" in that way.
// arr1[0] = "Hey";//this array is coming from another file and the data is fine
var arr2 = [];
arr2[0] = arr1[0];
arr2[0] += "1"; // right now arr1 and arr2 both has "Hey1" in them.
Any ideas?
Thank You
An array is an object in Javascript. As you might know objects are copied by reference. You could take a look here: What is the most efficient way to deep clone an object in JavaScript?
You can do a deep, rather than a shallow, copy of an array of strings like this:
var arr2 = [], i = 0;
for (i = 0; i < arr1.length; i++) {
arr2[i] = String(arr1[i]);
}
EDITED: oops, swapped deep and shallow.
I have a set of arrays named in the following fashion: question0, question1, question2 etc.
I also have a variable that corresponds to the question number.
With this, how would I access array question0 without having to type out the whole name. For example, in a for loop, I have if the loop number is 5, I want to do an operation on question5. I know this is really simple, but I haven't been able to find the solution.
Variables ending in sequential numbers are usually a hint to use arrays. Sounds like you need an array of arrays instead, and then you can just:
doOperation(question[somenumber])
Why not just use a big array, question, where each item it itself an array?
That aside, if the variables are global then you could use window['question'+i], with i being the number of the question.
Don't use variable names with an ordinal number as their suffix; use the proper structures, such as an array:
var questions = ['why?', 'what?', 'where?'],
nr = 2; // the question number
alert(questions[nr]);
In my example, each "question" is a string, but it could be any other structure, including another array.
I think it would be simpler to have your question(n) values as an array. From there you could use the following: questions[i] where i represents the current loop number, thus improving manipulation.
var questions = [["What?", "Why?"], ["When?", "How?"]];
for(var i = 0; i < questions.length; i++) {
for(var j = 0; j < questions[i].length; j++) {
console.info(questions[i][j]);
}
}