Confused about arrays on javascript - javascript

I want to make the next array based on another 2 arrays:
array1 = ['a', 'b']
array2 = [1,2,3]
I want to create the next array
newArray = [['a',1], ['a',2], ['a',3], ['b',1], ['b',2], ['b',3]]
Here is my code:
var test1 = ['a', 'b'];
var test2 = [1,2,3], arr1 = [], arr2 = [];
for(var i = 0; i < test1.length; i++){
arr1 = [];
arr1.push(test1[i]);
for(var x = 0; x < test2.length; x++){
if(arr1.length > 1)
arr1.pop();
arr1.push(test2[x])
arr2.push(arr1);
}
}
console.log("arr1:",JSON.stringify(arr1), "arr2:" ,JSON.stringify(arr2));
But it returns the last element of the second array.
[['a',3], ['a',3], ['a',3], ['b',3], ['b',3], ['b',3]]
Why is this happening?

Every other answer about array lengths, and similar things are not right. The only reason you get 3 (or whatever the last value/length is) all over the place is because Arrays are by reference, and functions, not for-loops create lexical scope. This is one of the reasons you hear that 'functions are first-class citizens in javascript'. This is a classical example, and frequently in interviews too, used to trip up devs who are not used to how scoping in javascript really behaves. There are some ways to fix it that involve wrapping the innards of loops in functional scopes, and passing in the index, but I'd like to suggest a more 'javascript centric' approach, and that is to solve the problem with functions.
See this example (which by the way is also a clear way to implement your goal.)
var test1 = ['a', 'b'];
var test2 = [1,2,3];
// this will iterate over array 1 and return
// [[ [a,1],[a,2],[a,3] ],[ [b,1],[b,2],[b,3] ]]
var merged = test1.map(function(item1){
return test2.map(function(item2){
return [item1, item2];
});
});
//this is a slick way to 'flatten' the result set
var answer = [].concat.apply([],merged )
console.log(answer) //this is it.
Functions () make scope - not 'brackets' {}. The easiest fix is usually to use functions to solve your problems as they create lexical scope. The most trusted library on npm, lodash, for instance is based on this. I think you'll write less and less loops from day to day js as you progress, and use more functions.
Working example on js fiddle:
https://jsfiddle.net/3z0hh12y/1/
You can read more about scopes and closures here
https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch1.md
And one more thing: when you think you want a loop in js, you usually want Array.map(), especially if you're remapping values.

You problem lies in the second loop. because you have a single reference to ary1 you are over writing the value with each loop.
so first time it loops your array will have
[['a',1]]
but because you you only have one reference to ary1 you are just editing the value you just pushed into ary2.
so then you get this:
[['a',2],['a',2]]
you may think that you are pushing a new array in but it is in fact the same exact array! so the pattern continues and you get the result that you are seeing.

It's occurring because you're popping elements off arr1 once it's length exceeds 1, so the last element is all that persists.
Try this:
var test1 = ['a', 'b'];
var test2 = [1,2,3];
var arr1 = [], arr2 = [];
for(var i = 0; i < test1.length; i++) {
for(var x = 0; x < test2.length; x++) {
arr1[arr1.length] = [test1[i], test2[x]];
}
}
console.log(JSON.stringify(arr1));

Beside the solutions for fixed style for two array, you might use another approach to get the result. you could use an iterative and recursive approach for variable length of parts an their length.
function combine(array) {
function c(part, index) {
array[index].forEach(function (a) {
var p = part.concat([a]);
if (p.length === array.length) {
r.push(p);
return;
}
c(p, index + 1);
});
}
var r = [];
c([], 0);
return r;
}
console.log(combine([['a', 'b'], [1, 2, 3]]));
console.log(combine([['a', 'b', 'c'], ['1', '2', '3', '4'], ['A', 'B']]));
console.log(combine([['a', 'b', 'c'], ['1', '2', '3', '4'], [['A'], ['B']]]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

I guess the proper functional approach would be done by a single liner reduce and nested map duo.
var arr = ['a', 'b'],
brr = [1,2,3],
result = arr.reduce((p,c) => p.concat(brr.map(e => [c,e])),[]);
console.log(JSON.stringify(result));

your approach is a bit off, you better take this approach (which is pretty simple I think): DEMO
var array1 = ['a', 'b'],
array2 = [1,2,3],
nextArray=[];
for(var i=0, array1Length=array1.length; i < array1Length; i++){
for(var x=0, array2Length=array2.length; x < array2Length; x++){
nextArray.push([array1[i],array2[x]]);
}
}
console.log(nextArray);

Yeah, that's way more complicated than it needs to be. The result you want is called the Cartesian product, and can be generated like this:
const cartesianProduct = (a, b) => {
const rv = [];
a.map(ae => b.map(be => rv.push([ae, be])));
return rv;
};
const array1 = ['a', 'b']
const array2 = [1,2,3]
console.log(JSON.stringify(cartesianProduct(array1, array2)));
If Javascript6 had flatMap it would be even simpler:
const cartesianProduct = (a, b) =>
a.flatMap(ae => b.map(be => [ae, be]));

I modified your code a little (but not too much, I tried to keep the same approach). The solution was to create a new array (arr1) in the inner loop. Otherwise, the first correct pair ['a', 1] would get overridden just after begin pushed to arr2 at the next loop pass.
var test1 = ['a', 'b'];
var test2 = [1,2,3];
var arr2 = [];
for(var i = 0; i < test1.length; i++){
for(var x = 0; x < test2.length; x++){
var arr1 = [];
arr1.push(test1[i]);
if(arr1.length > 1){
arr1.pop();
}
arr1.push(test2[x]);
arr2.push(arr1);
}
}

Related

Can I use Array.prototype.some() to check if two arrays have two common elements? [duplicate]

I have a target array ["apple","banana","orange"], and I want to check if other arrays contain any one of the target array elements.
For example:
["apple","grape"] //returns true;
["apple","banana","pineapple"] //returns true;
["grape", "pineapple"] //returns false;
How can I do it in JavaScript?
Vanilla JS
ES2016:
const found = arr1.some(r=> arr2.includes(r))
ES6:
const found = arr1.some(r=> arr2.indexOf(r) >= 0)
How it works
some(..) checks each element of the array against a test function and returns true if any element of the array passes the test function, otherwise, it returns false. indexOf(..) >= 0 and includes(..) both return true if the given argument is present in the array.
vanilla js
/**
* #description determine if an array contains one or more items from another array.
* #param {array} haystack the array to search.
* #param {array} arr the array providing items to check for in the haystack.
* #return {boolean} true|false if haystack contains at least one item from arr.
*/
var findOne = function (haystack, arr) {
return arr.some(function (v) {
return haystack.indexOf(v) >= 0;
});
};
As noted by #loganfsmyth you can shorten it in ES2016 to
/**
* #description determine if an array contains one or more items from another array.
* #param {array} haystack the array to search.
* #param {array} arr the array providing items to check for in the haystack.
* #return {boolean} true|false if haystack contains at least one item from arr.
*/
const findOne = (haystack, arr) => {
return arr.some(v => haystack.includes(v));
};
or simply as arr.some(v => haystack.includes(v));
If you want to determine if the array has all the items from the other array, replace some() to every()
or as arr.every(v => haystack.includes(v));
ES6 solution:
let arr1 = [1, 2, 3];
let arr2 = [2, 3];
let isFounded = arr1.some( ai => arr2.includes(ai) );
Unlike of it: Must contains all values.
let allFounded = arr2.every( ai => arr1.includes(ai) );
Hope, will be helpful.
If you're not opposed to using a libray, http://underscorejs.org/ has an intersection method, which can simplify this:
var _ = require('underscore');
var target = [ 'apple', 'orange', 'banana'];
var fruit2 = [ 'apple', 'orange', 'mango'];
var fruit3 = [ 'mango', 'lemon', 'pineapple'];
var fruit4 = [ 'orange', 'lemon', 'grapes'];
console.log(_.intersection(target, fruit2)); //returns [apple, orange]
console.log(_.intersection(target, fruit3)); //returns []
console.log(_.intersection(target, fruit4)); //returns [orange]
The intersection function will return a new array with the items that it matched and if not matches it returns empty array.
ES6 (fastest)
const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
a.some(v=> b.indexOf(v) !== -1)
ES2016
const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
a.some(v => b.includes(v));
Underscore
const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
_.intersection(a, b)
DEMO: https://jsfiddle.net/r257wuv5/
jsPerf: https://jsperf.com/array-contains-any-element-of-another-array
If you don't need type coercion (because of the use of indexOf), you could try something like the following:
var arr = [1, 2, 3];
var check = [3, 4];
var found = false;
for (var i = 0; i < check.length; i++) {
if (arr.indexOf(check[i]) > -1) {
found = true;
break;
}
}
console.log(found);
Where arr contains the target items. At the end, found will show if the second array had at least one match against the target.
Of course, you can swap out numbers for anything you want to use - strings are fine, like your example.
And in my specific example, the result should be true because the second array's 3 exists in the target.
UPDATE:
Here's how I'd organize it into a function (with some minor changes from before):
var anyMatchInArray = (function () {
"use strict";
var targetArray, func;
targetArray = ["apple", "banana", "orange"];
func = function (checkerArray) {
var found = false;
for (var i = 0, j = checkerArray.length; !found && i < j; i++) {
if (targetArray.indexOf(checkerArray[i]) > -1) {
found = true;
}
}
return found;
};
return func;
}());
DEMO: http://jsfiddle.net/u8Bzt/
In this case, the function could be modified to have targetArray be passed in as an argument instead of hardcoded in the closure.
UPDATE2:
While my solution above may work and be (hopefully more) readable, I believe the "better" way to handle the concept I described is to do something a little differently. The "problem" with the above solution is that the indexOf inside the loop causes the target array to be looped over completely for every item in the other array. This can easily be "fixed" by using a "lookup" (a map...a JavaScript object literal). This allows two simple loops, over each array. Here's an example:
var anyMatchInArray = function (target, toMatch) {
"use strict";
var found, targetMap, i, j, cur;
found = false;
targetMap = {};
// Put all values in the `target` array into a map, where
// the keys are the values from the array
for (i = 0, j = target.length; i < j; i++) {
cur = target[i];
targetMap[cur] = true;
}
// Loop over all items in the `toMatch` array and see if any of
// their values are in the map from before
for (i = 0, j = toMatch.length; !found && (i < j); i++) {
cur = toMatch[i];
found = !!targetMap[cur];
// If found, `targetMap[cur]` will return true, otherwise it
// will return `undefined`...that's what the `!!` is for
}
return found;
};
DEMO: http://jsfiddle.net/5Lv9v/
The downside to this solution is that only numbers and strings (and booleans) can be used (correctly), because the values are (implicitly) converted to strings and set as the keys to the lookup map. This isn't exactly good/possible/easily done for non-literal values.
Using filter/indexOf:
function containsAny(source,target)
{
var result = source.filter(function(item){ return target.indexOf(item) > -1});
return (result.length > 0);
}
//results
var fruits = ["apple","banana","orange"];
console.log(containsAny(fruits,["apple","grape"]));
console.log(containsAny(fruits,["apple","banana","pineapple"]));
console.log(containsAny(fruits,["grape", "pineapple"]));
You could use lodash and do:
_.intersection(originalTarget, arrayToCheck).length > 0
Set intersection is done on both collections producing an array of identical elements.
const areCommonElements = (arr1, arr2) => {
const arr2Set = new Set(arr2);
return arr1.some(el => arr2Set.has(el));
};
Or you can even have a better performance if you first find out which of these two arrays is longer and making Set out for the longest array, while applying some method on the shortest one:
const areCommonElements = (arr1, arr2) => {
const [shortArr, longArr] = (arr1.length < arr2.length) ? [arr1, arr2] : [arr2, arr1];
const longArrSet = new Set(longArr);
return shortArr.some(el => longArrSet.has(el));
};
I wrote 3 solutions. Essentially they do the same. They return true as soon as they get true. I wrote the 3 solutions just for showing 3 different way to do things. Now, it depends what you like more. You can use performance.now() to check the performance of one solution or the other. In my solutions I'm also checking which array is the biggest and which one is the smallest to make the operations more efficient.
The 3rd solution may not be the cutest but is efficient. I decided to add it because in some coding interviews you are not allowed to use built-in methods.
Lastly, sure...we can come up with a solution with 2 NESTED for loops (the brute force way) but you want to avoid that because the time complexity is bad O(n^2).
Note:
instead of using .includes() like some other people did, you can use
.indexOf(). if you do just check if the value is bigger than 0. If
the value doesn't exist will give you -1. if it does exist, it will give you
greater than 0.
indexOf() vs includes()
Which one has better performance? indexOf() for a little bit, but includes is more readable in my opinion.
If I'm not mistaken .includes() and indexOf() use loops behind the scene, so you will be at O(n^2) when using them with .some().
USING loop
const compareArraysWithIncludes = (arr1, arr2) => {
const [smallArray, bigArray] =
arr1.length < arr2.length ? [arr1, arr2] : [arr2, arr1];
for (let i = 0; i < smallArray.length; i++) {
return bigArray.includes(smallArray[i]);
}
return false;
};
USING .some()
const compareArraysWithSome = (arr1, arr2) => {
const [smallArray, bigArray] =
arr1.length < arr2.length ? [arr1, arr2] : [arr2, arr1];
return smallArray.some(c => bigArray.includes(c));
};
USING MAPS Time complexity O(2n)=>O(n)
const compararArraysUsingObjs = (arr1, arr2) => {
const map = {};
const [smallArray, bigArray] =
arr1.length < arr2.length ? [arr1, arr2] : [arr2, arr1];
for (let i = 0; i < smallArray.length; i++) {
if (!map[smallArray[i]]) {
map[smallArray[i]] = true;
}
}
for (let i = 0; i < bigArray.length; i++) {
if (map[bigArray[i]]) {
return true;
}
}
return false;
};
Code in my:
stackblitz
I'm not an expert in performance nor BigO so if something that I said is wrong let me know.
You can use a nested Array.prototype.some call. This has the benefit that it will bail at the first match instead of other solutions that will run through the full nested loop.
eg.
var arr = [1, 2, 3];
var match = [2, 4];
var hasMatch = arr.some(a => match.some(m => a === m));
I found this short and sweet syntax to match all or some elements between two arrays. For example
// OR operation. find if any of array2 elements exists in array1. This will return as soon as there is a first match as some method breaks when function returns TRUE
let array1 = ['a', 'b', 'c', 'd', 'e'], array2 = ['a', 'b'];
console.log(array2.some(ele => array1.includes(ele)));
// prints TRUE
// AND operation. find if all of array2 elements exists in array1. This will return as soon as there is a no first match as some method breaks when function returns TRUE
let array1 = ['a', 'b', 'c', 'd', 'e'], array2 = ['a', 'x'];
console.log(!array2.some(ele => !array1.includes(ele)));
// prints FALSE
Hope that helps someone in future!
Just one more solution
var a1 = [1, 2, 3, 4, 5]
var a2 = [2, 4]
Check if a1 contain all element of a2
var result = a1.filter(e => a2.indexOf(e) !== -1).length === a2.length
console.log(result)
What about using a combination of some/findIndex and indexOf?
So something like this:
var array1 = ["apple","banana","orange"];
var array2 = ["grape", "pineapple"];
var found = array1.some(function(v) { return array2.indexOf(v) != -1; });
To make it more readable you could add this functionality to the Array object itself.
Array.prototype.indexOfAny = function (array) {
return this.findIndex(function(v) { return array.indexOf(v) != -1; });
}
Array.prototype.containsAny = function (array) {
return this.indexOfAny(array) != -1;
}
Note: If you'd want to do something with a predicate you could replace the inner indexOf with another findIndex and a predicate
Here is an interesting case I thought I should share.
Let's say that you have an array of objects and an array of selected filters.
let arr = [
{ id: 'x', tags: ['foo'] },
{ id: 'y', tags: ['foo', 'bar'] },
{ id: 'z', tags: ['baz'] }
];
const filters = ['foo'];
To apply the selected filters to this structure we can
if (filters.length > 0)
arr = arr.filter(obj =>
obj.tags.some(tag => filters.includes(tag))
);
// [
// { id: 'x', tags: ['foo'] },
// { id: 'y', tags: ['foo', 'bar'] }
// ]
Good perfomance solution:
We should transform one of arrays to object.
const contains = (arr1, mainObj) => arr1.some(el => el in mainObj);
const includes = (arr1, mainObj) => arr1.every(el => el in mainObj);
Usage:
const mainList = ["apple", "banana", "orange"];
// We make object from array, you can use your solution to make it
const main = Object.fromEntries(mainList.map(key => [key, true]));
contains(["apple","grape"], main) // => true
contains(["apple","banana","pineapple"], main) // => true
contains(["grape", "pineapple"], main) // => false
includes(["apple", "grape"], main) // => false
includes(["banana", "apple"], main) // => true
you can face with some disadvantage of checking by in operator (eg 'toString' in {} // => true), so you can change solution to obj[key] checker
Adding to Array Prototype
Disclaimer: Many would strongly advise against this. The only time it'd really be a problem was if a library added a prototype function with the same name (that behaved differently) or something like that.
Code:
Array.prototype.containsAny = function(arr) {
return this.some(
(v) => (arr.indexOf(v) >= 0)
)
}
Without using big arrow functions:
Array.prototype.containsAny = function(arr) {
return this.some(function (v) {
return arr.indexOf(v) >= 0
})
}
Usage
var a = ["a","b"]
console.log(a.containsAny(["b","z"])) // Outputs true
console.log(a.containsAny(["z"])) // Outputs false
My solution applies Array.prototype.some() and Array.prototype.includes() array helpers which do their job pretty efficient as well
ES6
const originalFruits = ["apple","banana","orange"];
const fruits1 = ["apple","banana","pineapple"];
const fruits2 = ["grape", "pineapple"];
const commonFruits = (myFruitsArr, otherFruitsArr) => {
return myFruitsArr.some(fruit => otherFruitsArr.includes(fruit))
}
console.log(commonFruits(originalFruits, fruits1)) //returns true;
console.log(commonFruits(originalFruits, fruits2)) //returns false;
When I looked at your answers, I could not find the answer I wanted.
I did something myself and I want to share this with you.
It will be true only if the words entered (array) are correct.
function contains(a,b) {
let counter = 0;
for(var i = 0; i < b.length; i++) {;
if(a.includes(b[i])) counter++;
}
if(counter === b.length) return true;
return false;
}
let main_array = ['foo','bar','baz'];
let sub_array_a = ['foo','foobar'];
let sub_array_b = ['foo','bar'];
console.log(contains(main_array, sub_array_a)); // returns false
console.log(contains(main_array,sub_array_b )); // returns true
Array .filter() with a nested call to .find() will return all elements in the first array that are members of the second array. Check the length of the returned array to determine if any of the second array were in the first array.
getCommonItems(firstArray, secondArray) {
return firstArray.filter((firstArrayItem) => {
return secondArray.find((secondArrayItem) => {
return firstArrayItem === secondArrayItem;
});
});
}
It can be done by simply iterating across the main array and check whether other array contains any of the target element or not.
Try this:
function Check(A) {
var myarr = ["apple", "banana", "orange"];
var i, j;
var totalmatches = 0;
for (i = 0; i < myarr.length; i++) {
for (j = 0; j < A.length; ++j) {
if (myarr[i] == A[j]) {
totalmatches++;
}
}
}
if (totalmatches > 0) {
return true;
} else {
return false;
}
}
var fruits1 = new Array("apple", "grape");
alert(Check(fruits1));
var fruits2 = new Array("apple", "banana", "pineapple");
alert(Check(fruits2));
var fruits3 = new Array("grape", "pineapple");
alert(Check(fruits3));
DEMO at JSFIDDLE
Not sure how efficient this might be in terms of performance, but this is what I use using array destructuring to keep everything nice and short:
const shareElements = (arr1, arr2) => {
const typeArr = [...arr1, ...arr2]
const typeSet = new Set(typeArr)
return typeArr.length > typeSet.size
}
Since sets cannot have duplicate elements while arrays can, combining both input arrays, converting it to a set, and comparing the set size and array length would tell you if they share any elements.
With underscorejs
var a1 = [1,2,3];
var a2 = [1,2];
_.every(a1, function(e){ return _.include(a2, e); } ); //=> false
_.every(a2, function(e){ return _.include(a1, e); } ); //=> true
Vanilla JS with partial matching & case insensitive
The problem with some previous approaches is that they require an exact match of every word. But, What if you want to provide results for partial matches?
function search(arrayToSearch, wordsToSearch) {
arrayToSearch.filter(v =>
wordsToSearch.every(w =>
v.toLowerCase().split(" ").
reduce((isIn, h) => isIn || String(h).indexOf(w) >= 0, false)
)
)
}
//Usage
var myArray = ["Attach tag", "Attaching tags", "Blah blah blah"];
var searchText = "Tag attach";
var searchArr = searchText.toLowerCase().split(" "); //["tag", "attach"]
var matches = search(myArray, searchArr);
//Will return
//["Attach tag", "Attaching tags"]
This is useful when you want to provide a search box where users type words and the results can have those words in any order, position and case.
Update #Paul Grimshaw answer, use includes insteed of indexOf for more readable
let found = arr1.some(r=> arr2.indexOf(r) >= 0)
let found = arr1.some(r=> arr2.includes(r))
A short way of writing this:
const found = arr1.some(arr2.includes)
I came up with a solution in node using underscore js like this:
var checkRole = _.intersection(['A','B'], ['A','B','C']);
if(!_.isEmpty(checkRole)) {
next();
}
You are looking for intersection between the two arrays. And you have two major intersection types: 'every' and 'some'. Let me give you good examples:
EVERY
let brands1 = ['Ford', 'Kia', 'VW', 'Audi'];
let brands2 = ['Audi', 'Kia'];
// Find 'every' brand intersection.
// Meaning all elements inside 'brands2' must be present in 'brands1':
let intersectionEvery = brands2.every( brand => brands1.includes(brand) );
if (intersectionEvery) {
const differenceList = brands1.filter(brand => !brands2.includes(brand));
console.log('difference list:', differenceList);
const commonList = brands1.filter(brand => brands2.includes(brand));
console.log('common list:', commonList);
}
If condition is not met (like if you put 'Mercedes' in brands2) then 'intersectionEvery' won't be satisfied - will be bool false.
If condition is met it will log ["Ford", "VW"] as difference and ["Kia", "Audi"] as common list.
Sandbox: https://jsfiddle.net/bqmg14t6/
SOME
let brands1 = ['Ford', 'Kia', 'VW', 'Audi'];
let brands2 = ['Audi', 'Kia', 'Mercedes', 'Land Rover'];
// Find 'some' brand intersection.
// Meaning some elements inside 'brands2' must be also present in 'brands1':
let intersectionSome = brands2.some( brand => brands1.includes(brand) );
if (intersectionSome) {
const differenceList = brands1.filter(brand => !brands2.includes(brand));
console.log('difference list:', differenceList);
const commonList = brands1.filter(brand => brands2.includes(brand));
console.log('common list:', commonList);
}
Here we are looking for some common brands, not necessarily all.
It will log ["Ford", "VW"] as difference and ["Kia", "Audi"] as common brands.
Sandbox: https://jsfiddle.net/zkq9j3Lh/
Personally, I would use the following function:
var arrayContains = function(array, toMatch) {
var arrayAsString = array.toString();
return (arrayAsString.indexOf(','+toMatch+',') >-1);
}
The "toString()" method will always use commas to separate the values. Will only really work with primitive types.
console.log("searching Array: "+finding_array);
console.log("searching in:"+reference_array);
var check_match_counter = 0;
for (var j = finding_array.length - 1; j >= 0; j--)
{
if(reference_array.indexOf(finding_array[j]) > 0)
{
check_match_counter = check_match_counter + 1;
}
}
var match = (check_match_counter > 0) ? true : false;
console.log("Final result:"+match);

How sort arrays in js

There are arrays A and B. We need to add to array C all the values of arrays A and B that are equal in both value and indexes.
A = [a,b,c], B = [c,b,a], C = [b]
Also: to add to array D all unique values from array A that are contained in array B.
A = [d,a,b,c], B = [c,b,a,a], D = [a,b,c]
Is it possible to do this without a nested loop? I can handle the first task, but how do I fill D with values?
for (let i = 0; i < a.length; i++) {
if (b[i] === a[i]) {
c.push(a[i]);
} else if() {
// Some code
}
}
filter method? (for second question)
let D = A.filter(e => B.includes(e));
adding because you asked for D to contain unique values from A, thanks to #jarmod for pointing this out. You could use filter again to remove duplicates. I found this: Get all unique values in a JavaScript array (remove duplicates)
You can use a Set to keep track of unique values and .has() for efficient lookup in that Set. This code uses only one loop in your code, but several set operations use loops in their internal implementation (to build a set from an Array or convert a set to an Array). That cannot be avoided.
const A = ['e', 'd', 'a', 'b', 'c'];
const B = ['e', 'c', 'b', 'a', 'a'];
function processArrays(a, b) {
const c = [];
const aSet = new Set(a);
const commonSet = new Set();
for (let i = 0; i < a.length; i++) {
if (b[i] === a[i]) {
c.push(a[i]);
}
// if aSet has this value, then add it to commonSet
if (aSet.has(b[i])) {
commonSet.add(b[i])
}
}
return { samePositionElements: c, commonElements: Array.from(commonSet) };
}
console.log(processArrays(A, B));
Note, I don't do an if/else here because these are two independent output tests. The first is if the two elements in the same position have the same value. The second is whether it's an element in common with the other array (regardless of position).
This code assumes the two input arrays have the same length. If you wish to support inputs with different length, that can be accommodated with slightly more code.
Simple Way and Fast Solution:
let A = ['a','b','c', 'e'];
let B = ['c','b','a', 'e'];
let common =[];
for(let i=0; i<A.length && i<B.length; i++){
if(A[i]==B[i]){
common.push(A[i])
}
}
console.log(common)

How to loop through multiple arrays, within an array of arrays using a single value for an index?

I'm trying to solve a problem where you have an array
array = [[a,b,c],[e,f,g],[h,i,j]]
I want to loop through the first letter of the first array, then look at the first of all the other arrays then do a comparison whether they're equal or not. I'm unsure how to do this given that a loop will go through everything in its array. I wrote a nested loop below, but I know it's know it's not the right approach. I basically want something that looks
like
if (array[0][0] == array[1][0] == array[2][0]), then repeat for each element in array[0]
var firstWord = array[0];
var remainderWords = array.slice(1);
for(var i = 0; i < firstWord.length; i++){
for (var j = 0; i< remainderWords.length; j++){
if firstWord[i] == remaindersWord[j][i]
}
Any help would be appreciated.
Use Array.every() to check that a condition is true for all elements of an array.
firstWord.forEach((letter, i) => {
if (remainderWords.every(word => word[i] == letter)) {
// do something
}
});
You can use three nested for or .forEach loops to get to the items in the remainderItems array. Try this
var array = [['a', 'b', 'c'], ['b', 'f', 'g'], ['h', 'c', 'j']];
var firstWord = array[0];
var remainderWords = array.slice(1);
firstWord.forEach((l, idx) => {
remainderWords.forEach(arr => {
arr.forEach(v => {
if (l == v) {
// matched do whatever you want with the variable here
console.log(v)
}
})
})
})

Find the newly added elements of an Array of Objects with Lodash

Imagine we have two Arrays.
var a = [B, C, E];
var b = [A, B, C, D, E];
Array a is our default Array that we have saved locally.
Now the api we fetch from sends us the new version of this Array a called b.
How can I use lodash so I can get the difference of this two arrays so I get in this case
[A, D] returned ?
UPDATE:
I came up with my own solution it kinda worked, so only try this if the accepted answer does not work for some reason:
const getObjectDiff = (newArr, oldArr) => {
if (_.isEqual(newArr, oldArr)) {
return true;
} else {
const checkLength = newArr.length;
const checkerLength = oldArr.length;
var indexes = [];
var falseIndexes = [];
var allIndexes = [];
for (let i = 0; i <= checkerLength; i++) {
for (let j = 0; j <= checkLength - 1; j++) {
allIndexes.push(i);
if (_.isEqual(newArr[i], oldArr[j])) {
indexes.push(i);
} else {
falseIndexes.push(i);
}
}
}
const falseUniqueIndexes = _.uniq(falseIndexes);
return _.difference(falseUniqueIndexes, indexes);
}
};
```
We can use _.differenceWith along with the _.isEqual to check deep equality between objects.
_.isEqual will perform a deep comparison between two objects to see if they are equivalent so we can use this to compare, say, objects that have been decoded from JSON.
This is a simple example, however, this will work with much more complex objects as long as they are equal (as determined by lodash)
const apiResponseA = '[{"id":"B"},{"id":"C"},{"id":"E"}]';
const apiResponseB = '[{"id":"A"},{"id":"B"},{"id":"C"},{"id":"D"},{"id":"E"}]'
const a = JSON.parse(apiResponseA);
const b = JSON.parse(apiResponseB);
console.log("a:", apiResponseA)
console.log("b:", apiResponseB)
console.log("Difference:", JSON.stringify(_.differenceWith(b,a, _.isEqual)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
I realize you asked specifically for a lodash solution, but I just want to mention that you could do this pretty simply without a 3rd party library - just use Array.prototype.filter and Array.prototype.includes, like this:
var a = ['B', 'C', 'E'];
var b = ['A', 'B', 'C', 'D', 'E'];
function getDifference(a, b) {
return b.filter(letter => !a.includes(letter));
}
console.log(getDifference(a, b));

Get all possible set of combinations of two arrays as an array of arrays with JavaScript

Please note: the linked question, "How can I create every combination possible for the contents of two arrays?" does not solve this particular question. The persons that labeled that did not fully understand this specific permutation and request.
If you have two arrays (arr1, arr2) with n elements in each array (i.e., each array will be the same length), then the question is: What's the best method to get/determine all the possible matches where elements do not match with other elements in the same array and where order does not matter?
For example, let's say I have:
arr1 = ["A","B","C"];
arr2 = ["Z","Y","X"];
I would like to get back an array of arrays where each element of one array is paired with an element of another array. So the result would be a unique set of arrays:
matches = [
[["A","Z"],["B","Y"],["C","X"]],
[["A","Z"],["B","X"],["C","Y"]],
[["A","Y"],["B","X"],["C","Z"]],
[["A","Y"],["B","Z"],["C","X"]],
[["A","X"],["B","Z"],["C","Y"]],
[["A","X"],["B","Y"],["C","Z"]],
]
Please note, these two arrays would be the same:
[["A","Z"],["B","Y"],["C","X"]]
[["B","Y"],["C","X"],["A","Z"]]
I am trying to do this with vanilla JavaScript but am completely open to using Lodash as well. For an added bonus, since this can get out of control, speed and performance are important. But right now, I am just trying to get something that would yield a proper result set. To limit this, this function would probably not be used with more than two arrays of 50 elements each.
Here is my latest attempt (using lodash):
function getMatches(arr1, arr2){
var matches = [];
for (var arr1i = 0, arr1l = arr1.length; arr1i < arr1l; arr1i++) {
for (var arr2i = 0, arr2l = arr2.length; arr2i < arr2l; arr2i++) {
matches.push(_(arr1).zip(arr2).value());
arr2.push(arr2.shift());
}
}
return matches;
}
[[A, 1], [B, 2]]
is the same as
[[B, 2], [A, 1]]
in your case, which means that the solution depends on what you pair to the first elements of your array. You can pair n different elements as second elements to the first one, then n - 1 different elements as second elements to the second one and so on, so you have n! possibilities, which is the number of possible permutations.
So, if you change the order of the array elements but they are the same pair, they are equivalent, so you could view the first elements as a fixed ordered set of items and the second elements as the items to permutate.
Having arr1 = [a1, ..., an] and arr2 = [b1, ..., bn] we can avoid changing the order of a1. So, you permutate the inner elements and treat the outer elements' order as invariant, like:
const permutations = function*(elements) {
if (elements.length === 1) {
yield elements;
} else {
let [first, ...rest] = elements;
for (let perm of permutations(rest)) {
for (let i = 0; i < elements.length; i++) {
let start = perm.slice(0, i);
let rest = perm.slice(i);
yield [...start, first, ...rest];
}
}
}
}
var other = ['A', 'B', 'C'];
var myPermutations = permutations(['X', 'Y', 'Z']);
var done = false;
while (!done) {
var next = myPermutations.next();
if (!(done = next.done)) {
var output = [];
for (var i = 0; i < next.value.length; i++) output.push([other[i], next.value[i]]);
console.log(output);
}
}
You're just looking for permutations. The first elements of your tuples are always the same, the second ones are permuted so that you get all distinct sets of combinations.
const arr1 = ["A","B","C"];
const arr2 = ["Z","Y","X"];
const result = permutate(arr2).map(permutation =>
permutation.map((el, i) => [arr1[i], el])
);
This implementation uses Typescript and Lodash.
const permutations = <T>(arr: T[]): T[][] => {
if (arr.length <= 2)
return arr.length === 2 ? [arr, [arr[1], arr[0]]] : [arr];
return reduce(
arr,
(acc, val, i) =>
concat(
acc,
map(
permutations([...slice(arr, 0, i), ...slice(arr, i + 1, arr.length)]),
vals => [val, ...vals]
)
),
[] as T[][]
);
};

Categories