how to match the value of two variables in Jquery - javascript

I was just wondering how I can match the value of two variable, for example if I have
var A = [1,2,3];
var b = [A,B,C];
how can I output the first value of each and second value of each and so on, so the output will become
A1,B2,C3
thanks

Using jQuery.map:
var a = ['A','B','C'];
var b = [1,2,3];
var result = $.map(a, function(n, i){
return n + b[i];
}); // ["A1", "B2", "C3"]

Related

How to deduplicate a merged array?

I want to merge two arrays which have some duplicated values into one array which has no duplicates. I am using concat but the result is all value.
var a = [1,2,2];
var b = [1,2,3,3];
var c = a.concat(b);
console.log(c);
Expected output:
[1, 2, 3]
Merge them into a Set, and turn that set back into an array:
var a = [1,2,2];
var b = [1,2,3,3];
var c = [...new Set([...a, ...b])];
console.log(c);
You can also use concat and Array.from as an alternative to spread syntax if necessary:
var a = [1,2,2];
var b = [1,2,3,3];
var c = Array.from(new Set(a.concat(b)));
console.log(c);
Add both of them to a Set, which is a data structure that ignores duplicates.

Pushing an Object to Array in js

I'm trying to push an Object to an Array using the following command:
a = a.concat(b);
a = [];
b = {a: Object1, b: Object2 ....};
So I wan to have array a to be like a = [Object1, Object2...]
But the above statement results in:
a = [[Object1, Object2...][Object11, Object12...]];
How can I achieve this in JS?
If I´m understanding what you want, you want just objects, not the keys. So, could be:
for( var key in b ){
var value = b[key];
a.push(value);
}
console.log(JSON.stringify(a));
Hope it helps...
You are concatenating two arrays with Array.concat() you need to use Array.push().
var a = [ObjectA];
var b = ObjectB;
a.push(b);
// a = [ObjectA, ObjectB];
let a = [];
let b = {a:1, b:2, c:3};
for(obj in b){
let val = {};
val[obj] = b[obj];
a.push(val);
}
console.log(a);
Did you mean something like this ?
The Object.values() method returns an array of a given object's own enumerable property values,
You could use the Object values method Object.values(), like :
Object.values(b);
Example :
var a = [];
var obj_1 = {'attr_1': 'val_1', 'attr_2': 'val_2'};
var obj_2 = {'attr_3': 'val_3', 'attr_4': 'val_4'};
var b = {'a': obj_1, 'b': obj_2};
a = Object.values(b);
console.log( a );
Hope this helps.

Push object into array does not work as expected

My goal is to create an array like this:
[{"str":"a","number":1},{"str":"a","number":2},{"str":"b","number":1},{"str":"b","number":2}]
so I wrote this javascript
abc = ["a","b"]
num = [1,2]
arr = []
a = {}
for (var i in abc)
{
str = abc[i]
a.str = str;
for(var x in num)
{
number = num[x]
a.number = number
console.log(a)
arr.push(a)
}
}
the console log looks fine, but the array looks like this:
[{"str":"b","number":2},{"str":"b","number":2},{"str":"b","number":2},{"str":"b","number":2}]
Can anyone could explain this?
This is happening because you are actually working with a reference to the same object, thus modifying the same over and over.
To fix it you must declare a new object in every iteration you want to use a different one.
Try something like this:
var abc = ["a", "b"];
var num = [1, 2];
var arr = [];
for (var i in abc) {
for (var x in num) {
var a = {};
a.str = abc[i];
a.number = num[x];
arr.push(a);
}
}
console.log(arr);
Also, don't forget to declare your variables with var or let and end your statements with ;.
As said in the comments, you’ve pushed your a object to arr many times, instead of adding four separate objects. To fix this issue, you could declare a in the for (var x in num) loop, every time as a new object (using const or let). But I’ve simplified it further, see the code below.
To iterate through JavaScript arrays, you should use .forEach method.
let abc = ['a', 'b'];
let num = [1, 2];
let arr = [];
abc.forEach(letter => {
num.forEach(number => {
arr.push({number: number, str: letter});
});
});
abc = ["a","b"]
num = [1,2]
arr = []
for (var i in abc)
{
for(var x in num)
{
a = {} ---------------- Reset "a"
str = abc[i] --------------------- 1
a.str = str; --------------------- 2
number = num[x]
a.number = number
console.log(a)
arr.push(a)
}
}
console.log(arr)
// Move 1 and 2 inside the second loop
Using map :
let tempArray = abc.map((e,i) => { return num.map((ee,ii) => { return {"str": e, "number": ee }; } ) });
$.merge(tempArray[0], tempArray[1]);

How to extract value from an array of array

I have an array of array stored. I need to extract the particular value from this arrays.
e.g allarray contain the list of arrays
allarray= [Array[3],Array[3],Array[3]] are three arrays present in that.
0:Array[3]
0:"a1"
1:"b1"
2:"c1"
1:Array[3]
0:"a2"
1:"b2"
2:"c2"
3:Array[3]
0:"a3"
1:"b3"
2:"c3"
I need to extract this c1,c2 and c3 from the above arrays and display in the alert box.
Can anyone tell me how i can do that?
i tried with $.each but unfortunately doesn't work. Can anyone?
If I understand you correctly, your array looks like this
var allarray = [["a1","b1","c1"],["a2","b2","c2"],["a3","b3","c3"]];
To get c1, c2, and c3 you could just do this
var c1 = allarray[0][2], c2 = allarray[1][2], c3 = allarray[2][2];
or you could do a loop to put all of the cs in a single array of its own
var cs = [];
for(var i = 0; i < allarray.length; i++) {
cs.push(allarray[i][2]);
}
This is what the Array.prototype.map function is for:
var arr = [["a1","b1","c1"],["a2","b2","c2"],["a3","b3","c3"]];
var theValues = arr.map(function(inner) {return inner[2]});
alert(theValues.join(', '));
Can try using map(). Example:
var allarray = [["a1","b1","c1"],["a2","b2","c2"],["a3","b3","c3"]],
index = 2;
allarray.map(function(val, ind){
document.write(allarray[ind][index] + '<br />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
var allarray = [
["a1", "b1", "c1"],
["a2", "b2", "c2"],
["a3", "b3", "c3"]
],
num = 2;
//one by one
allarray.forEach(function( arr ) {
alert( arr[ num ] );
});
//or all at once
alert( allarray.map(function( arr ) { return arr[ num ]; }).join(',') );
var arrOfArr=[['a1','b1','c1'],['a2','b2','c2'],['a3','b3','c3']];
var cVals=arrOfArr.map(function(element,index){
return arrOfArr[index][2];
});
alert(cVals);
http://jsfiddle.net/3uaugbem/
You can access it by running
allarray[X][2]
where X is 0, 1, or 2 depending on which of the 3 arrays you want

Javascript/Jquery- new array from existing two arrays

I have two arrays
var a= $("#update-select1").val(); // gives value 1,2,4
var b= $("#update-select2").val(); // 1,2,5
I want two different arrays from the above two arrays.
//array has the values which is in `b` but not in `a`
var c = [5]
//another array has value in `a` but not in `b`
var d =[4]
You can use Array.filter this way:
var c = [1,2,5]
.filter(function(a){return this.indexOf(a) === -1},[1,2,4]); //=> [5]
var d = [1,2,4]
.filter(function(a){return this.indexOf(a) === -1},[1,2,5]); //=> [4]
Or:
function notIn(a){
return this.indexOf(a) === -1;
}
var a = [1,2,4]
,b = [1,2,5]
,c = b.filter(notIn,a)
,d = a.filter(notIn,b);
See also
You can try the grep() method
var a1 = [1, 2, 4];
var a2 = [1, 2, 5];
var difference = $.grep(a1, function (x) {
return $.inArray(x, a2) < 0
});
alert(" the difference is " + difference);​
JSFiddle
I know this is an old question, but I thought I would share this
little trick.
var diff = $(old_array).not(new_array).get();
diff now contains what was in old_array that is not in new_array
Found this on Compare 2 arrays which returns difference
try something like this
var a= [1,2,4];
var b= [1,2,5];
var c = [];
jQuery.each(b,function(k,v){
if(a.indexOf(v) < 0){
c.push(v);
}
})
console.log(c);//[5]
var d = [];
jQuery.each(a,function(k,v){
if(b.indexOf(v) < 0){
d.push(v);
}
})
console.log(d);//[4]

Categories