Finding Matches Between Multiple JavaScript Arrays

How can I find matching values in two arrays?

Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is > -1, then push it onto the returned array.

​Array.prototype.diff = function(arr2) {
var ret = [];
for(var i in this) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};


My solution doesn't use two loops like others do so it may run a bit faster. If you want to avoid using for..in, you can sort both arrays first to reindex all their values:

Array.prototype.diff = function(arr2) {
var ret = [];
this.sort();
arr2.sort();
for(var i = 0; i < this.length; i += 1) {
if(arr2.indexOf(this[i]) > -1){
ret.push(this[i]);
}
}
return ret;
};

Usage would look like:

var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];

console.log(array1.diff(array2));

If you have an issue/problem with extending the Array prototype, you could easily change this to a function.

var diff = function(arr, arr2) {

And you'd change anywhere where the func originally said this to arr2.

Finding matches between multiple JavaScript Arrays

var result = arrays.shift().filter(function(v) {
return arrays.every(function(a) {
return a.indexOf(v) !== -1;
});
});

DEMO: http://jsfiddle.net/nWjcp/2/

You could first sort the outer Array to get the shortest Array at the beginning...

arrays.sort(function(a, b) {
return a.length - b.length;
});

For completeness, here's a solution that deals with duplicates in the Arrays. It uses .reduce() instead of .filter()...

var result = arrays.shift().reduce(function(res, v) {
if (res.indexOf(v) === -1 && arrays.every(function(a) {
return a.indexOf(v) !== -1;
})) res.push(v);
return res;
}, []);

DEMO: http://jsfiddle.net/nWjcp/4/

How to find multiple elements in Array - Javascript ,ES6

You have to use filter at this context,

let names= ["Style","List","Raw"];
let results= names.filter(x => x.includes("s"));
console.log(results); //["List"]

If you want it to be case insensitive then use the below code,

let names= ["Style","List","Raw"];
let results= names.filter(x => x.toLowerCase().includes("s"));
console.log(results); //["Style", "List"]

To make it case in sensitive, we have to make the string's character all to lower case.

Find matching values in two arrays

You can use the combination of map and includes helper to achieve that.

let firstArray = ["One", "Two", "Three", "Four", "Five"];
let secondArray = ["Three", "Four"];
let jsonArray = [];

jsonArray = firstArray.map(i => {
return { 'name': i, 'matched': secondArray.includes(i) };
});

console.log(jsonArray);

compare two arrays and remove partial match in javascript

You should use some instead of every.

The some() method tests whether at least one element in the array
passes the test implemented by the provided function. It returns true
if, in the array, it finds an element for which the provided function
returns true; otherwise it returns false. It doesn't modify the array. - MDN

const arr1 = ["hello from the other side", "very nice boy,john"];
const arr2 = ["nice", "work"];

const result = arr2.filter((s) => !arr1.some((str) => str.includes(s)));
console.log(result);

Finding intersection between 2 arrays of objects with dynamic keys

if you want to compare with every index then you can do something like this

const hierarchy1 = [{
level1: 'Shoes',
level3: "xyz"
}]

const hierarchy2 = [{
level1: 'Shoes',
level2: 'Sneakers',
}, {
level3: "xyz"
}]

function intersection(arr1, arr2) {
let final = []
// loop over first array
for (let i = 0; i < arr1.length; i++) {
let element = arr1[i]
let temp = {}

// loop over all indexes of second array
for (let data of arr2) {
// check every key fro data to see if there's any intersection
Object.keys(data).forEach(key => {
if (data[key] === element[key] && key in element) {
temp[key] = element[key]
}
})
}
// if we found any intersection push it in final array
if (Object.keys(temp).length) {
final.push(temp)
}
}
return final
}

console.log(intersection(hierarchy1, hierarchy2))

How can I compare two arrays of objects and update value when properties match?

I'd suggest making a lookup table (totalByMonth) then you can just loop over the state and update each one by looking up the total in totalByMonth.

const state = [
{total: 0, month_name: "Jan"},
{total: 0, month_name: "Feb"},
{total: 0, month_name: "Mar"},
{total: 0, month_name: "Apr"}
];

const fetched = [
{total: 4, month_name: "Mar"},
{total: 1, month_name: "Apr"}
];

//build totalByMonth object
const totalByMonth = {};
for (let f of fetched) {
totalByMonth[f.month_name] = f.total;
}

//update state
for (let s of state) {
const total = totalByMonth[s.month_name];
if (total) s.total = total;
}

console.log(state);


Related Topics



Leave a reply



Submit