So here's the proposed problem.
Compare two arrays and return a new array with any items not found in both of the original arrays.
Here's what I have so far.
function diff(arr1, arr2) {
for (var a in arr1) {
for (var b in arr2) {
if (arr1[a] == arr2[b]){
arr2.splice(b,1);
}
}
}
return arr2;
}
diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);
This code basically just compares each value of the first array with the second one. If a match is found it then removes the item using the splice function.
This works great for arrays that are one dimensional but how can I get it to work for multidimensional arrays such as:
diff([1, 2, 3, 5], [1, [2, 3], [4, 5]]);
What if these arrays are not just two dimensions but any number of dimensions. I should be able to iterate through every element of every array no matter they are set up.
With lodash you can do this :
var a = [1, 2, 3, 5, 7], b = [1, [2, 3], [4, 5, [7]]];
var result = _.filter(_.flattenDeep(b), function(item){
return a.indexOf(item) === -1;
});
console.log(result);
$("body").append(JSON.stringify(result))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>
<body></body>
Related
This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed last year.
I have an argument that passes me a 2D array and I want to get the numbers from that array and put them on a normal array.
The argument passed to me = ([1, 3, 2], [5, 2, 1, 4], [2, 1])
What I want to do = [1, 3, 2, 5, 2, 1, 4, 2, 1]
Thanks in advance, I think I'm having a brain fart over here!
You can use the flat method of Array!
const arr = [[1, 2, 3], [4, 5, 6]]
console.log(arr.flat())
// [1, 2, 3, 4, 5, 6]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
Iterate the array and add all data in new array with concat() method.
var arr = [[1, 3, 2], [5, 2, 1, 4], [2, 1]];
var newArr = [];
for(var i = 0; i < arr.length; i++)
{
newArr = newArr.concat(arr[i]);
}
console.log(newArr);
You can use array flat method to convert 2d array to 1d array
const arr = [
[1,2,3],
[4,5,6]
].flat(1); //flat(depth:Number)
console.log(arr);
// [1,2,3,4,5,6]
Im trying to copy elements of arr1 into arr2 at index n. The elements must be copied in the exact order they're in. I can get the code to work when I loop through the arrow backwards but I cant pass the tests because its not in order.
function frankenSplice(arr1, arr2, n) {
let newArr = arr2.splice(" ");
for(let i = 0; i < arr1.length;i++) {
newArr.splice(n,0,arr1[i]);
}
return console.log(newArr);
}
An example of how this should be called is frankenSplice([1, 2, 3], [4, 5, 6], 1);
Expected output is [4, 1, 2, 3, 5]
I keep getting [ 4, 1, 2, 3, 5, 6 ]
The reason your output is coming backwards is because you keep inserting at the same position n. This pushes the previous element after it, so they end up in reverse order. If you increment n each time through the loop, you'll insert them in order.
But there's no need for a loop, use spread syntax to use all of arr1 as the arguments in a single call to splice().
function frankenSplice(arr1, arr2, n) {
let newArr = [...arr2]; // make copy of arr2
newArr.splice(n, 0, ...arr1); // splice arr1 into the copy
return newArr;
}
console.log(frankenSplice([1, 2, 3], [4, 5, 6], 1));
I don't understand why you don't expect 6 in the output.
Not sure why the 6 is getting deleted but maybe something like this:
function frankenSplice(arr1, arr2, n) {
let newArr = arr2
newArr.splice(n+1)
for(let i = arr1.length - 1; i >= 0; i--) {
newArr.splice(n,0,arr1[i]);
}
return console.log(newArr);
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
I would like to compare multiple array and finally have an array that contain all unique values from different array. I tried to:
1,Use the filter method to compare the difference between 2 arrays
2,Call a for loop to input the arrays into the filter method
and the code is as follows
function diffArray(arr1, arr2) {
function filterfunction (arr1, arr2) {
return arr1.filter(function(item) {
return arr2.indexOf(item) === -1;
});
}
return filterfunction (arr1,arr2).concat(filterfunction(arr2,arr1));
}
function extractArray() {
var args = Array.prototype.slice.call(arguments);
for (var i =0; i < args.length; i++) {
diffArray(args[i],args[i+1]);
}
}
extractArray([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]);
However it does not work and return the error message "Cannot read property 'indexOf' of underfined" .... What's wrong with the logic and what should I change to make it works?
Many thanks for your help in advance!
Re: For all that mark this issue as duplicated ... what I am looking for, is a solution that can let me to put as many arrays as I want for input and reduce all the difference (e.g input 10000 arrays and return 1 array for unique value), but not only comparing 2 arrays .. The solutions that I have seen are always with 2 arrays only.
I don't use filters or anything of the sort but it will get the job done. I first create an empty array and concat the next array to it. Then I pass it to delete the duplicates and return the newly "filtered" array back for use.
function deleteDuplicates(a){
for(var i = a.length - 1; i >= 0; i--){
if(a.indexOf(a[i]) !== i){
a.splice(i, 1);
}
}
return a;
}
function extractArray() {
var args = Array.prototype.slice.call(arguments), arr = [];
for (var i = 0; i < args.length; i++) {
arr = deleteDuplicates(arr.concat(args[i]));
}
return arr;
}
var arr = extractArray([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]);
console.log(arr) //[3, 2, 5, 1, 7, 4, 6]
This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
How to detect array equality in JavaScript?
(4 answers)
Closed 6 years ago.
How do I check for equality between the elements of two arrays without using external libraries (and preferably using ES5)?
I want to check for equality between them without caring about the order of the elements. So the two arrays [1,2,3] and [2,3,1] are equal in my situation.
I guess I should write a function
function isEqual(arr1, arr2) {
arr1.forEach(el => {
if (arr2.indexOf(el) === -1) {
return false;
}
});
arr2.forEach(el => {
if (arr1.indexOf(el) === -1) {
return false;
}
});
return true;
}
You can use JSON.stringify and Array#sort methods. Sort both the arrays ang compare them after converting to JSON string.
function isEqual(arr1, arr2) {
return JSON.stringify(arr1.sort()) === JSON.stringify(arr2.sort());
}
console.log(isEqual([1, 2, 3], [2, 3, 1]));
console.log(isEqual([1, 2, 3], [2, 4, 1]));
console.log(isEqual([1, 2, 3, 3], [2, 3, 1]));
console.log(isEqual([1, 2, 3, 3], [2, 4, 1, 1]));
Or instead of JSON.stringify you can also use Array#join method( Suggested by #JonCarter ) which makes it little more simple.
function isEqual(arr1, arr2) {
return arr1.sort().join() === arr2.sort().join();
}
console.log(isEqual([1, 2, 3], [2, 3, 1]));
console.log(isEqual([1, 2, 3], [2, 4, 1]));
console.log(isEqual([1, 2, 3, 3], [2, 3, 1]));
console.log(isEqual([1, 2, 3, 3], [2, 4, 1, 1]));
You could use Array#every to assert the values are equal. This is very rudimentary though as uses a strict equality check which has its limitations. But this shows the rough framework for a iterating over the array.
NOTE: Since arrays are index based lists it is assumed that for them to be equal they would need to have equal values at the same index.
var arr1 = [1,2,3,4];
var arr2 = [1,2,3,4];
var arr3 = [1,2,4];
var arr4 = [1,2,2,4];
function isArrEql(a1, a2) {
return a1.length === a2.length && a1.every(function(v, i) {
return v === a2[i];
});
}
console.log('arr1, arr2: ', isArrEql(arr1, arr2));
console.log('arr1, arr2: ', isArrEql(arr1, arr3));
console.log('arr1, arr2: ', isArrEql(arr1, arr4));
I have the following array:
var array = [
[1, 2, 3, 4, 5],
[2, 3],
[3, 4],
[3]
];
I'm trying to end up with a unique set of numbers from the arrays that appear in all arrays.
Therefore in this case returning
[3]
Any suggestions?
Many thanks :)
Store the value of array[0] in a variable (let's call it result).
Loop from array[1] to the end.
In this loop, run through all the values of result. If the current value of result is not in array[x] remove this value from result.
At the end of the loop, result only contains the desired values.
Aside from the obvious "iterate over every array and find matching numbers in every other array" you could flatten (concat) the original array, sort it, then look for numbers that occur at four consecutive indexes. I'm not a fan of questions where OP doesn't show any effort, but this was quite fun, so here it goes
array.reduce(function(prev, cur){
return prev.concat(cur);
})
.sort()
.filter(function(item, i, arr){
return arr[ i + array.length - 1 ] === item;
});
Or ES2015:
array.reduce((prev, cur)=>prev.concat(cur))
.sort()
.filter((i, idx, arr)=>(arr[idx+array.length-1]===i));
After learning i was using the wrong javascript method to remove from an array (pop) and some more tinkering. I got it working many thanks for those who responded.
var array = [
[2, 3, 5, 1],
[3, 4, 2, 1],
[3, 2],
[3, 4, 2, 5]
];
var result = array[0]
for (var i = 1; i < array.length; i++) {
for (var j = 0; j < result.length; j++) {
var arrayQuery = $.inArray(result[j], array[i]);
if(arrayQuery == -1){
result.splice(j, 1)
}
};
};
Try this:
var array = [
[1, 2, 3, 4, 5],
[2, 3],
[3, 4],
[3]
];
var arr = [];
for(var x in array){
for(var y in array[x]){
if(arr.indexOf(array[x][y]) === -1){
arr.push(array[x][y]);
}
}
}
console.log(arr);
Output:
[1, 2, 3, 4, 5]
Working Demo