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
.
how to find best matching element in array of numbers?
xs = ["77.5", "80", "82.5", "85", "87.5", "90", "95", "100", "105"]
xs.min_by { |x| (x.to_f - 82.4).abs }
#=> "82.5"
Find all matching elements with in an array of objects
Two things: first, Array.find()
returns the first matching element, undefined
if it finds nothing. Array.filter
returns a new array containing all matching elements, []
if it matches nothing.
Second thing, if you want to match 4,5
, you have to look into the string instead of making a strict comparison. To make that happen we use indexOf
which is returning the position of the matching string, or -1
if it matches nothing.
Example:
const arr = [
{
name: 'string 1',
arrayWithvalue: '1,2',
other: 'that',
},
{
name: 'string 2',
arrayWithvalue: '2',
other: 'that',
},
{
name: 'string 2',
arrayWithvalue: '2,3',
other: 'that',
},
{
name: 'string 2',
arrayWithvalue: '4,5',
other: 'that',
},
{
name: 'string 2',
arrayWithvalue: '4',
other: 'that',
},
];
const items = arr.filter(item => item.arrayWithvalue.indexOf('4') !== -1);
console.log(items);
How to find the best match for an object in an array?
Linear search:
<script>
function FindBestMatch( a, item )
{
var bestIndex = null;
var bestNumMatch = -1;
var bestNumMismatch = 0;
var numItemElements = item.length;
for (var i in a)
{
for (var numMatch=0; numMatch<numItemElements; numMatch++)
{
if (a[i][numMatch]!=item[numMatch]) break;
}
var numMismatch = a[i].length - numMatch;
if (numMatch==numItemElements && !numMismatch) return i;
if (numMatch>bestNumMatch
|| (numMatch==bestNumMatch && numMismatch<bestNumMismatch))
{
bestIndex = i;
bestNumMatch = numMatch;
bestNumMismatch = numMismatch;
}
}
return bestIndex;
}
var myArray = [
[ 'UserA', 'Bob Smith', 12345, 'hello' ],
[ 'UserA', 'Bob Smith', 12345 ],
[ 'UserA', 'Bob Smith', 123 ],
[ 'UserA', 'Bob Smith' ],
[ 'UserA', 'Bob Smith', 12345, 'hello' ]
];
var someItem = [ 'UserA', 'Bob Smith', 2222 ];
var i = FindBestMatch(myArray,someItem);
alert("The best match is number "+i+":\n\n"+myArray[i].join(" | "));
</script>
Best way to find matching id's in an array of objects?
I would combine the filter
and map
array methods. Use filter
to get a list of genres that are in your movies
array, then use map
to convert that to a list of names.
Example:
const movies = [28, 14, 100, 53, 37]
const genres = [ {id: 28, name: "Action"}, {id: 10770, name: "TV Movie"}, {id: 53, name: "Thriller"}, {id: 10752, name: "War"}, {id: 37, name: "Western"} ]
// I would like to return an array of the matching ids. example [ 'Action', 'Thriller', 'Western' ].
console.log(genres.filter(g => movies.includes(g.id)).map(g => g.name))
How to compare two arrays and find best match?
f = pow(arrX[0]-findarr[0],2) + pow(arrX[1]-findarr[1],2) + pow(arrX[2]-findarr[2],2);
pow(x,2) == x*x
So, "the best match" will be array, with smallest f
Best way to search for repeated values in a Multidimensional array in javascript
You can write a generic groupAdjacent
function. It has two parameters -
t
- the input arrayequal
- a function to test if elements are considered adjacent
function groupAdjacent(t, equal)
{ function* run (r, q, i)
{ if (i >= t.length)
return yield [...r, q]
if (equal(q, t[i]))
return yield* run([...r, q], t[i], i + 1)
yield [...r, q]
yield* run([], t[i], i + 1)
}
return t.length
? Array.from(run([], t[0], 1))
: []
}
Next we define two functions specific to your particular teams
data -
teamAdjacent
- determines what makes a team adjacencyteamSort
- compares two teams for sorting
const teamAdjacent = (a, b) =>
a[1] == b[1] && a[2] == b[2] // w/l is equal
const teamSort = (a, b) =>
a[3] - b[3] // sort by sortKey, ascending
Finally we tie everything together. groupAdjacent
creates an array of groups, then we .sort
each group, and lastly call .flat
to return an un-grouped result
-
const result =
groupAdjacent(teams, teamAdjacent)
.map(_ => _.sort(teamSort))
.flat()
console.log(result)
['Team A', 25, 2, 88]
['Team D', 20, 7, 54]
['Team E', 20, 7, 65]
['Team C', 20, 7, 76]
['Team B', 20, 7, 84]
['Team F', 20, 6, 34]
['Team G', 19, 8, 67]
['Team H', 20, 7, 11]
['Team N', 3, 24, 33]
Expand the snippet to verify the results in your own browser -
function groupAdjacent(t, equal)
{ function* run (r, q, i)
{ if (i >= t.length)
return yield [...r, q]
if (equal(q, t[i]))
return yield* run([...r, q], t[i], i + 1)
yield [...r, q]
yield* run([], t[i], i + 1)
}
return t.length
? Array.from(run([], t[0], 1))
: []
}
const teamAdjacent = (a, b) =>
a[1] == b[1] && a[2] == b[2] // w/l is equal
const teamSort = (a, b) =>
a[3] - b[3] // sort by sortKey, ascending
const teams =
[ ['Team A', 25, 2, 88]
, ['Team B', 20, 7, 84]
, ['Team C', 20, 7, 76]
, ['Team D', 20, 7, 54]
, ['Team E', 20, 7, 65]
, ['Team F', 20, 6, 34]
, ['Team G', 19, 8, 67]
, ['Team H', 20, 7, 11]
, ['Team N', 3, 24, 33]
]
const result =
groupAdjacent(teams, teamAdjacent)
.map(_ => _.sort(teamSort))
.flat()
console.log(result)
Related Topics
How to Print Something Without a New Line in Ruby
Rails Pass Params/Arguments to Activerecord Callback Function
How to Embed Dynamic Ruby Code to "Javascript" Section in Slim Templates
Marking an Unused Block Variable
Rails Way to Detect Mobile Device
Rails First_Or_Create Activerecord Method
How to Set a Request.Referrer Inside My Rspec
Run Code Only If Script Called from the Command Line
Memory Size of a Hash or Other Object
Ruby Code Beautification, Split Long Instructions on Multiple Lines
Ruby on Rails User Registration Using Rest API Call and Devise
Is There a Workaround to Open Urls Containing Underscores in Ruby