Javascript/Jquery- new array from existing two arrays - javascript

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]

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.

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]);

Integer arrays comparison

I have a question of JS arrays.
Example:
var fullArr = [1,2,3,4];
var partArr = [2,3];
var newArr = [];
We have a main array fullArr and a partial array partarr. I want to create a function/filter, which is looking for existing items in fullArr and not in partArr.
In this example above newArr must be equal to [1,4].
I've tried doing something like this, but it's not working properly.
for (var k in fullArray) { // [1,2,3,4]
for (var j in selectedArray) { // [1,4]
if (fullArray[k] == selectedArray[j]) {
newArray.splice(selectedArray[j] - 1, 1); // must be [2,3]
break;
}
}
}
What is a good way of making this? Thanks.
Here's one
var newArr = fullArr.filter(function(f) { // The filter() method creates a new array with all elements that pass the test implemented by the provided function.
return partArr.indexOf(f) == -1; // The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
})
to impress the girls, you can also
var newArr = fullArr.filter(function(f) {
return !~partArr.indexOf(f);
})
Here is the code for your requirement.
var fullArr = [1,2,3,4];
var partArr = [2,3];
var newArr = [];
for(var i=0;i<fullArr.length;i++){
if(partArr.indexOf(fullArr[i]) == -1)
newArr.push(fullArr[i]);
};
Here is the working Link
Hope it works :)
In fact, you want a common part between arrays. Obviously you can choose splice or indexOf to have O(n * m) or even O(m * n^2) performance. It's obviously suboptimal for any array larger than few elements
Or you can use objects as hash maps to find differences in (in worst case) O(n + m log m):
var fullArr = [1,2,3,4];
var partArr = [2,3];
var temporaryObject = Object.create(null);
partArr.forEach(el=>temporaryObject[el] = true); // temporaryObject after this operation is {"2": true, "3": true}
var newArr = fullArr.filter(el=>temporaryObject[el]);
In this example I have used ES6 feature called "arrow functions". It translates to following ES5 code:
var partArr = [2, 3];
var temporaryObject = Object.create(null);
partArr.forEach(function (el) {
temporaryObject[el] = true;
}); // temporaryObject after this operation is {"2": true, "3": true}
var newArr = fullArr.filter(function (el) {
return temporaryObject[el];
});
You can use the filter() function that works on arrays:
var newArr = fullArr.filter(function(val, i, arr) {
return partArr.indexOf(val) === -1;
});
This will return a new array containing the values of every iteration that returns true.
Should you ever need to do this on an object in the future a great way is to first convert the object keys to an array and then run the filter:
Object.keys(myObj).function(val, i, arr) {
return partArr.indexOf(val) === -1;
});
Here are few other approaches:
var fullArr = [1,2,3,4];
var partArr = [2,3];
var newArr = [];
1.
fullArr.map(function(element){
if(partArr.indexOf(element) === -1) newArr.push(element);
})
console.log(newArr);
2.
for(i in fullArr){
if(partArr.indexOf(fullArr[i]) === -1) newArr.push(fullArr[i]);
}
console.log(newArr);
3.
fullArr.forEach(function(element){
if(partArr.indexOf(element) === -1) newArr.push(element);
})
console.log(newArr);

How to combine arrays in JavaScript? [duplicate]

This question already has answers here:
Javascript equivalent of Python's zip function
(24 answers)
Closed 8 years ago.
var arrayOne = [a,b,c];
var arrayTwo = [d,e,f];
How can I combine the two arrays in JavaScript so that the result will be:
var array = [a,d,b,e,c,f];
Note: This is not concatenating two arrays. This is merging the two arrays so the indices look like [0,0,1,1,2,2].
Assuming that the two arrays are equal of length, this should do the trick:
var arrayThree = [];
for(var i = 0; i < arrayOne.length; i++){
arrayThree.push(arrayOne[i], arrayTwo[i]);
}
If they aren't the same length and you would have the two arrays:
var a = [a,b,c,d];
var b = [e,f];
I assume you would want the the following result
var c = [a,e,b,f,c,d];
That should do the trick:
var c = [];
while(Math.min(a.length, b.length)){
c = c.concat(a.splice(0,1), b.splice(0,1));
//Or c = c.concat(b.splice(0,1), a.splice(0,1));
//depending on the order
}
a.length ? c = c.concat(a) : c = c.concat(b);
//Here is a = [c,d] and b = []
You can use jQuery's unique method along with concat
var a = [1,2,3];
var b = [2,3,4];
var c = a.concat(b); // [1,2,3,2,3,4]
c = $.unique(c); // [1, 2, 3, 4]
You may need to sort the array as needed.

Javascript merge 2 arrays and sum same key values

I have 2 array:
var array1 = [[5,10],[6,10],[7,10],[8,10],[9,10]];
var array2 = [[1,10],[2,10],[3,10],[4,10],[5,40],[6,40]];
Want to get 1 merged array with the sum of corresponding keys;
var array1 = [[1,10],[2,10],[3,10],[4,10],[5,50],[6,50],[7,10],[8,10],[9,10]];
Both arrays have unique keys, but the corresponding keys needs to be summed.
I tried loops, concat, etc but can't get the result i need.
anybody done this before?
You can use .reduce() to pass along an object that tracks the found sets, and does the addition.
DEMO: http://jsfiddle.net/aUXLV/
var array1 = [[5,10],[6,10],[7,10],[8,10],[9,10]];
var array2 = [[1,10],[2,10],[3,10],[4,10],[5,40],[6,40]];
var result =
array1.concat(array2)
.reduce(function(ob, ar) {
if (!(ar[0] in ob.nums)) {
ob.nums[ar[0]] = ar
ob.result.push(ar)
} else
ob.nums[ar[0]][1] += ar[1]
return ob
}, {nums:{}, result:[]}).result
If you need the result to be sorted, then add this to the end:
.sort(function(a,b) {
return a[0] - b[0];
})
This is one way to do it:
var sums = {}; // will keep a map of number => sum
// for each input array (insert as many as you like)
[array1, array2].forEach(function(array) {
//for each pair in that array
array.forEach(function(pair) {
// increase the appropriate sum
sums[pair[0]] = pair[1] + (sums[pair[0]] || 0);
});
});
// now transform the object sums back into an array of pairs
var results = [];
for(var key in sums) {
results.push([key, sums[key]]);
}
See it in action.
a short routine can be coded using [].map()
var array1 = [[5,10],[6,10],[7,10],[8,10],[9,10]];
var array2 = [[1,10],[2,10],[3,10],[4,10],[5,40],[6,40]];
array1=array2.concat(array1).map(function(a){
var v=this[a[0]]=this[a[0]]||[a[0]];
v[1]=(v[1]||0)+a[1];
return this;
},[])[0].slice(1);
alert(JSON.stringify(array1));
//shows: [[1,10],[2,10],[3,10],[4,10],[5,50],[6,50],[7,10],[8,10],[9,10]]
i like how it's just 3 line of code, doesn't need any internal function calls like push() or sort() or even an if() statement.
Try this:
var array1 = [[5,10],[6,10],[7,10],[8,10],[9,10]];
var array2 = [[1,10],[2,10],[3,10],[4,10],[5,40],[6,40]];
var res = [];
someReasonableName(array1, res);
someReasonableName(array2, res);
function someReasonableName(arr, res) {
var arrLen = arr.length
, i = 0
;
for(i; i < arrLen; i++) {
var ar = arr[i]
, index = ar[0]
, value = ar[1]
;
if(!res[index]) {
res[index] = [index, 0];
}
res[index][1] += value;
}
}
console.log(JSON.stringify(res, null, 2));
So, the result may have holes. Just like 0th index. Use the below function if you want to ensure there are no holes.
function compact(arr) {
var i = 0
, arrLen = arr.length
, res = []
;
for(i; i < arrLen; i++) {
var v = arr[i]
;
if(v) {
res[res.length] = v;
}
}
return res;
}
So, you can do:
var holesRemoved = compact(res);
And finally if you don't want the 0th elem of res. Do res.shift();
Disclaimer: I am not good with giving reasonable names.
The simple solution is like this.
function sumArrays(...arrays) {
const n = arrays.reduce((max, xs) => Math.max(max, xs.length), 0);
const result = Array.from({ length: n });
return result.map((_, i) => arrays.map(xs => xs[i] || 0).reduce((sum, x) => sum + x, 0));
}
console.log(...sumArrays([0, 1, 2], [1, 2, 3, 4], [1, 2])); // 2 5 5 4

Categories