Check whether elements from one array are present in another array - javascript

What is the best way to check whether elements from one array are present in another array using JavaScript?
I come up with two of the following methods (but neither of them do I like very much).
Method1
for(let i = 0; i < arr1.length; ++i) {
for(let j = 0; j < arr2.length; ++j) {
if(arr1[i] === arr2[j]) {
arr1[i].isPresentInArr2 = true;
break;
}
}
}
Method2
const idToObj = {};
for(let i = 0; i < arr2.length; ++i) {
nameToObj[arr2[i].Id] = arr2[i];
}
for(let i = 0; i < arr1.length; ++i) {
if(nameToObj[arr1[i].Id]) {
nameToObj[arr1[i].Id].isPresentInArr2 = true;
}
}
Here I am assuming that I have two arrays of objects: arr1 and arr2. Those objects have a unique Id property each. And I am to check whether every object in arr1 is present in arr2.
I suppose the second method would be more efficient. Hope for interesting suggestions.

in terms of Algorithm Complexity wise , It's like trade-offs .
First One - Space time Complexity - 0, Run time complexity - 0(n2)
Second One - Space time Complexity - o(n), Run time complexity - 0(n)
If it's performance focussed , go for second one .
In terms of js way , you have many ways . Read about includes() and indexOf() inbuilt method in javascript to avoid writing a loop . Also make use of javascript map function . You could also uses underscore.js
Ref Check if an array contains any element of another array in JavaScript for more details .

You could sort the arrays, then check if they are equal to one another:
var array1 = [4, 304, 2032], // Some random array
array2 = [4, 2032, 304];
function areEqual(array1, array2) {
if (array1.sort().toString() == array2.sort().toString()) {
// They're equal!
document.getElementById("isEqual").innerHTML = ("Arrays are equal");
return true;
} else {
// They're not equal.
document.getElementById("isEqual").innerHTML = ("Arrays aren't equal");
return false;
}
}
areEqual(array1, array2);
<!DOCTYPE html>
<html>
<body>
<p id="isEqual"></p>
</body>
</html>

You could get a list of Ids, then sort the id's and compare the two array lists of Ids using JSON.stringify
// Test arrays to work with
const array1 = [{Id:10},{Id:11},{Id:13},{Id:12}]
const array2 = [{Id:10},{Id:11},{Id:12},{Id:13}]
const array3 = [{Id:10},{Id:11},{Id:12}]
function test(arr1, arr2) {
// Map of each array [0, 1, 2, etc...]
let map1 = arr1.map(i => i.Id)
let map2 = arr2.map(i => i.Id)
// Sort each array from lowest to highest
// Note: Some kind of sort is required if we are going to compare JSON values
map1.sort()
map2.sort()
// Test the mapped arrays against each other
return JSON.stringify(map1) === JSON.stringify(map2)
}
console.log(test(array1, array2))
console.log(test(array1, array3))

map over the arrays of objects to produce arrays of ids, then use every and includes to check the elements in one array against the elements of the other: ids1.every(el => ids2.includes(el)).
Here's a working example:
const arr1 = [{ id: 0 }, { id: 1 }, { id: 2 }];
const arr2 = [{ id: 0 }, { id: 1 }, { id: 2 }];
const arr3 = [{ id: 14 }, { id: 1 }, { id: 2 }];
const getIds = (arr) => arr.map(el => el.id)
function check(arr1, arr2) {
const ids1 = getIds(arr1);
const ids2 = getIds(arr2);
return ids1.every(el => ids2.includes(el));
}
console.log(check(arr1, arr2));
console.log(check(arr1, arr3));

Related

How to get a value of column 'b' from a 2d array where column 'a' matches a single array in javascript

New to javascript. Need some guidance on the problem below:
I have these arrays:
array1 = [['a1'], ['a2'], ['a3']];
array2 = [['a1',4], ['a3',3], ['a6',2]];
How can i get the matching arrays whereby array1 first col = array2 first col?
Example expected result:
[['a1',4], ['a3',3]]
I hope the question makes sense. Not really sure how to approach this since the structure of these two arrays are different.
You can use filter to filter out the elements. Inside filter method check if elements exist in array1. You can flat array1 to check effeciently.
let flatArr1 = array1.flat(); //["a1", "a2", "a3"]
const result = array2.filter(([x,y]) => flatArr1.includes(x));
console.log(result) // for instance
This is my solution for your problem:
const compare = (array1, array2) => {
let matched = [];
const keys = [].concat(...array1);
for(let i = 0; i < array2.length; i++) {
for(let j = 0; j < array2.length; j++) {
let result = array2[i][j];
if(keys.includes(result)) {
matched.push(array2[i])
}
}
}
console.log("matched: ", matched);
};

comparing array of objects and assigning similarity score

I am attempting to compare two array of object and assigning them a similarity score based of common items in the array.
I was able to compare the arrays but I am running into issue with using the same concept on array of objects.
let array1 = [{key1:['item1','item2','item3','item4']},{key2:['event3','event4']}];
let array2 = [{key1:['item1','item4','item2','item8']},{key2:['event4','event2']}];
let arrayA=['item1','item2','item3','item4'];
let arrayB=['item1','item4','item2','item8'];
function SimilarityPercentage(arrayA,arrayB){
let answer =arrayA.filter(function(item) {
return arrayB.indexOf(item) >= 0;
}).length
return answer/(Math.max(arrayA.length,arrayB.length))*100
}
console.log(SimilarityPercentage(arrayA,arrayB));// 75
Given array1 and array2 , I would like the result split out a similarity score, similar to the function above. I would like to use the rand index calculation : https://en.wikipedia.org/wiki/Rand_index#targetText=The%20Rand%20index%20or%20Rand,is%20the%20adjusted%20Rand%20index.
You could get the values and calculate the common score.
function similarityPercentage(arrayA, arrayB) {
return 100 * arrayA.filter(Set.prototype.has, new Set(arrayB)).length / Math.max(arrayA.length, arrayB.length);
}
function similarities(a, b) {
var parts = a.map((o, i) => similarityPercentage(Object.values(o)[0], Object.values(b[i])[0]));
return parts.reduce((a, b) => a + b, 0) / parts.length;
}
var array1 = [{ key1: ['item1', 'item2', 'item3', 'item4'] }, { key2: ['event3', 'event4'] }],
array2 = [{ key1: ['item1', 'item4', 'item2', 'item8'] }, { key2: ['event4', 'event2'] }],
arrayA = ['item1', 'item2', 'item3', 'item4'],
arrayB = ['item1', 'item4', 'item2', 'item8'];
console.log(similarityPercentage(arrayA, arrayB)); // 75
console.log(similarities(array1, array2)); // 62.5
You could do something like this:
var array1 = [val1,val2,val3];
var array2 = [val1,val4,val5];
var sim = [];
var simscore = 9;
if (array1.length > array2.length) {
for (var i = 0; i < array1.length; i++) {
if(array1[i] == array2[i]) {
sim.push(i);
simarr = array1;
simscore ++;
}
}
}else{
for (var i = 0; i < array2.length; i++) {
if(array1[i] == array2[i]) {
sim.push(i);
simarr = array2;
simscore ++;
}
}
}
console.log(sim);
console.log("Percent similar: ", simscore/simarr.length);
This will add the similar index to an array sim and increase the count of similar indexes by 1, always for the longer array, then print the percent of similarity.
First of all, your sample arrays are not well-structured, and your problem can be done more quickly if you restructure them.
Since you have not provided a formula for calculating the similarity between array1 and array2, I assume that every each of these arrays has equal length, and every item in them represents an object which has only one property (with the same name), and that property itself is an array. One obvious approach is to calculate every similarity score of the related child arrays of these two arrays to be calculated and then calculate the total similarity by averaging every key's similarity score.
Assumptions:
array1 and array2 have equal length
The nth element of array1 has only one property with the name keyFoo and the nth element of array2 also has only one property with the name keyFoo and keyFoo property of these two arrays are arrays themselves and must be compared to each other.
This quickly can be done using already provided SimilarityPercentage function:
function SimilarityPercentage2 (array1, array2) {
let similaritySum = 0;
for (let i = 0; i < array1.length; i++) {
const elem = array1[i];
const key = Object.keys(elem)[0];
similaritySum += SimilarityPercentage(elem[key], array2[i][key]);
}
return similaritySum / array1.length;
}
console.log(SimilarityPercentage2(array1, array2));
// output: 62.5

Check if arrays contain shared elements regardless of index

I'd like to check if two arrays share elements regardless of order.
Given
array A: ['hello', 'how', 'are', 'you']
array B: ['how', 'are', 'hello']
Will return matches for 'hello', 'how', and 'are'
There seems to be something for PHP, array_intersect() (Check if array contains elements having elements of another array), but nothing for JavaScript.
I would use in if the values were in an object, but they are not:
if (key in obj) {
}
I could also do array.sort() to both arrays, but it's not guaranteed that both arrays will have same number of values. Therefore even if they are sorted, the compared indices would be off anyway.
How can I do this in JavaScript?
You can use filter to check if the same element is present in the other array.
var arr1 = ['hello', 'how', 'are', 'you'];
var arr2 = ['how', 'are', 'hello'];
var commonElements = arr1.filter(function(e) {
return arr2.indexOf(e) > -1;
});
console.log(commonElements);
You can also define this function on Array prototype
Array.prototype.intersection = function(arr) {
return this.filter(function(e) {
return arr.indexOf(e) > -1;
});
};
var arr1 = ['hello', 'how', 'are', 'you'],
arr2 = ['how', 'are', 'hello'];
var commonElements = arr1.intersection(arr2);
console.log(commonElements);
Considering performance I'd convert one of the array to an object, and then check intersection by traversing the other.
var arr1 = ['hello', 'how', 'are', 'you'];
var arr2 = ['how', 'are', 'hello'];
var set = {};
var intersect = [];
for (var i = 0; i < arr1.length; i++)
set[arr1[i]] = true;
for (var i = 0; i < arr2.length; i++)
if (set[arr2[i]]) intersect.push(arr2[i]);
But this method will ignore duplicate items in the arrays. And this may seem verbose compared to the filter and find solution. This may be helpful if you're doing intersection of large arrays.
In this approach, the first array is converted into a map, for fast lookup.
The second array is matched against the first.
The complexity is O(a) + O(b).
Pro: Elegance.
Con: Matching is continued after the overlap is detected.
function array_overlap(a, b) {
const lookup = a.reduce((m, n) => (m[n]=true, m), {});
const status = b.reduce((m, n) => (lookup[n] || m), false);
return status;
}
In ES6 syntax:
var intersection = arr1.filter( e => arr2.includes( e ) )

Get the array index of duplicates

In a JavaScript array how can I get the index of duplicate strings?
Example:
MyArray = ["abc","def","abc"]; //----> return 0,2("abc");
Another example:
My Array = ["abc","def","abc","xyz","def","abc"]
//----> return 0,2,5("abc") and 1,4("def");
I have no idea how to do this.
Thanks in advance for your help!
Update 01/2022: It's not 2013 anymore, and many things have changed. I neither recommend modifying the prototype, nor is the approach in this answer the "best" as it requires several iterations over the array.
Here's an updated version of the original answer, retaining its spirit, as well as the original answer below.
function getDuplicates<T>(input: T[]): Map<T, number[]> {
return input.reduce((output, element, idx) => {
const recordedDuplicates = output.get(element);
if (recordedDuplicates) {
output.set(element, [...recordedDuplicates, idx]);
} else if (input.lastIndexOf(element) !== idx) {
output.set(element, [idx]);
}
return output;
}, new Map<T, number[]>());
}
Yet another approach:
Array.prototype.getDuplicates = function () {
var duplicates = {};
for (var i = 0; i < this.length; i++) {
if(duplicates.hasOwnProperty(this[i])) {
duplicates[this[i]].push(i);
} else if (this.lastIndexOf(this[i]) !== i) {
duplicates[this[i]] = [i];
}
}
return duplicates;
};
It returns an object where the keys are the duplicate entries and the values are an array with their indices, i.e.
["abc","def","abc"].getDuplicates() -> { "abc": [0, 2] }
Another less sophisticated approach:
Iterate over the whole array and keep track of the index of each element. For this we need a string -> positions map. An object is the usual data type to use for this. The keys are the elements of the array and the values are arrays of indexes/positions of each element in the array.
var map = {};
for (var i = 0; i < arr.length; i++) {
var element = arr[i]; // arr[i] is the element in the array at position i
// if we haven't seen the element yet,
// we have to create a new entry in the map
if (!map[element]) {
map[element] = [i];
}
else {
// otherwise append to the existing array
map[element].push(i);
}
// the whole if - else statement can be shortend to
// (map[element] || (map[element] = [])).push(i)
}
Now you can iterate over the map and remove all entries where the array value has a length of one. Those are elements that appear only once in an array:
for (var element in map) {
if (map[element].length === 1) {
delete map[element];
}
}
Now map contains a string -> positions mapping of all duplicate elements of the array. For example, if you array is ["abc","def","abc","xyz","def","abc"], then map is an object of the form
var map = {
'abc': [0,2,5],
'def': [1,4]
};
and you can process it further in any way you like.
Further reading:
Eloquent JavaScript - Data structures: Objects and Arrays
MDN - Working with objects
MDN - Predefined core objects, Array object
This covers finding the indices efficiently:
var inputArray = [1, 2, 3, 4, 5, 6, 6, 7, 8, 9];
var encounteredIndices = {};
for(var i = 0; i < inputArray.length; i++)
if (encounteredIndices[inputArray[i]])
console.log(i); // Or add to some array if you wish
else
encounteredIndices[inputArray[i]] = 1;

Count unique elements in array without sorting

In JavaScript the following will find the number of elements in the array. Assuming there to be a minimum of one element in the array
arr = ["jam", "beef", "cream", "jam"]
arr.sort();
var count = 1;
var results = "";
for (var i = 0; i < arr.length; i++)
{
if (arr[i] == arr[i+1])
{
count +=1;
}
else
{
results += arr[i] + " --> " + count + " times\n" ;
count=1;
}
}
Is it possible to do this without using sort() or without mutating the array in any way? I would imagine that the array would have to be re-created and then sort could be done on the newly created array, but I want to know what's the best way without sorting.
And yes, I'm an artist, not a programmer, your honour.
The fast way to do this is with a new Set() object.
Sets are awesome and we should use them more often. They are fast, and supported by Chrome, Firefox, Microsoft Edge, and node.js.
— What is faster Set or Object? by Andrei Kashcha
The items in a Set will always be unique, as it only keeps one copy of each value you put in. Here's a function that uses this property:
function countUnique(iterable) {
return new Set(iterable).size;
}
console.log(countUnique('banana')); //=> 3
console.log(countUnique([5,6,5,6])); //=> 2
console.log(countUnique([window, document, window])); //=> 2
This can be used to count the items in any iterable (including an Array, String, TypedArray, and arguments object).
A quick way to do this is to copy the unique elements into an Object.
var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}
When this loop is complete the counts object will have the count of each distinct element of the array.
Why not something like:
var arr = ["jam", "beef", "cream", "jam"]
var uniqs = arr.reduce((acc, val) => {
acc[val] = acc[val] === undefined ? 1 : acc[val] += 1;
return acc;
}, {});
console.log(uniqs)
Pure Javascript, runs in O(n). Doesn't consume much space either unless your number of unique values equals number of elements (all the elements are unique).
Same as this solution, but less code.
let counts = {};
arr.forEach(el => counts[el] = 1 + (counts[el] || 0))
This expression gives you all the unique elements in the array without mutating it:
arr.filter(function(v,i) { return i==arr.lastIndexOf(v); })
You can chain it with this expression to build your string of results without sorting:
.forEach(function(v) {
results+=v+" --> " + arr.filter(function(w){return w==v;}).length + " times\n";
});
In the first case the filter takes only includes the last of each specific element; in the second case the filter includes all the elements of that type, and .length gives the count.
This answer is for Beginners. Try this method you can solve this problem easily. You can find a full lesson for reduce, filter, map functions from This link.
const user = [1, 2, 2, 4, 8, 3, 3, 6, 5, 4, 8, 8];
const output = user.reduce(function (acc, curr) {
if (acc[curr]) {
acc[curr] = ++acc[curr];
} else {
acc[curr] = 1;
}
return acc;
}, {});
console.log(output);
function reomveDuplicates(array){
var newarray = array.filter( (value, key)=>{
return array.indexOf(value) == key
});
console.log("newarray", newarray);
}
reomveDuplicates([1,2,5,2,1,8]);
Using hash Map with the time complexity O(n)
function reomveDuplicates(array){
var obj ={};
let res=[];
for( arg of array){
obj[arg] = true;
}
console.log(Object.keys(obj));
for(key in obj){
res.push(Number(key)); // Only if you want in Number
}
console.log(res);
}
reomveDuplicates([1,2,5,2,1,8]);
In a modern, extensible and easy-to-read approach, here's one using iter-ops library:
import {pipe, distinct, count} from 'iter-ops';
const arr = ['jam', 'beef', 'cream', 'jam'];
const count = pipe(arr, distinct(), count()).first;
console.log(count); //=> 3
function check(arr) {
var count = 0;
for (var ele of arr) {
if (typeof arr[ele] !== typeof (arr[ele+1])) {
count++;
} else {
("I don't know");
}
}
return count;
}

Categories

Resources