Compare two arrays of "strings" to check if they are equal [duplicate] - javascript

This question already has answers here:
Remove items from one array if not in the second array
(5 answers)
Closed 7 years ago.
Good day,
I have two arrays of strings. Strings are just numeric dates (eg: "01/01/2016"...).
I would like to know if there is a good/fast way to compare the two arrays and remove the strings from one array, which are not present in second one.
Example:
First array: ["01/01/2016","02/02/2015", "03/03/2014"]
Second array: ["01/01/2016", "02/02/2015"]
The string "03/03/2014" should be removed from the first array.
I have tried doing it though for() loops of both array lengths, but it seems to be very slow, because the arrays are big (abt. 1000+) indexes in each, like this:
for (var a = 0; a < oilDateArray.length; a++) {
for (var b = 0; b < fuelDateArray.length; b++) {
if (fuelDateArray[b] !== oilDateArray[a]) {
console.log("fuelDateArray not present: " + fuelDateArray[b]);
}
}
}
Is there a specific function/method, which I could use in order to perform the above operation faster?
Thanks in advance and have a nice day!

Try this :
for (var i = 0; i < firstArray.length; i++){
if (secondArray.indexOf(firstArray[i]) == -1){ // indexOf is -1 if not found
firstArray.splice(i, 1); // Remove 1 value at index i
i--; // To re-adjust the index value which is 1 less because of the splice
}
}
It may also be a bit slow, you can try with your array : https://jsfiddle.net/tyrsszaw/4

with jquery
$(array1).filter(array2);

If you have access to Set:
function intersect(arr1, arr2){
var s = new Set(arr1);
return arr2.filter(function(el){
return s.has(el);
});
}

i use jquery for array operations and i'll edit one for your need and paste here, i hope this can help you:
var arr1 = ["01/01/2016","02/02/2015", "03/03/2014"];
var arr2 = ["01/01/2016", "02/02/2015"];
var diff = [];
jQuery.grep(arr2, function(t) {
if (jQuery.inArray(t, arr1) == -1) diff.push(t);
});
alert(diff);​ // what was different will be alerted
i also found this code on stackoverflow sometime ago.
Update: Here is performance related topic you might be interested
Performance of jQuery.grep vs. Array.filter
tldr;
it says grep is about 3 times faster. So stick with my solution. :)

Related

How to print the 2 most repeated strings in an array [duplicate]

This question already has answers here:
Counting the occurrences / frequency of array elements
(39 answers)
Closed last year.
First of all I apologize this may be trivial but I'm stuck, I search in an array the string that repeats the most and print the 2 that repeat the most.
I have wanted to do Case or multiple if, but I also get the idea of a map(), in short I do not find an efficient way to implement it.
thank you very much in advance
const clientes=['cliente1','cliente2', 'cliente3', 'cliente2', 'cliente3', 'cliente4'];
for(let x = 0; x < clientes.length; x++)
{
}
console.log('CLIENTES', clientes)
Loop and count. your approach goes to right direction.
let counts = {};
const clientes = ['cliente1','cliente2', 'cliente3', 'cliente2', 'cliente3', 'cliente4'];
clientes.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts)

Compare multiple possible values of an array [duplicate]

This question already has answers here:
How to check if an array is a subset of another array in JavaScript?
(9 answers)
Closed 3 years ago.
So I have an array ["miranda","brad","johnny"] and I want to check if in the array the values are either equal to miranda or to john or even brad to return true one time and not three times if one or more of the names are present and if not It displays an error if any other value are in this array. Now to make my example clearer here is a snippet that would represent what I'm thinking of:
let array = ["miranda","brad","johnny"]
for(var i = 0; i < array.length;i++){
if(array[i] == "brad" || array[i] == "miranda" || array[i] == "john"){
console.log("success")
} else{
console.log("fail");
break;
}
}
Now my goal here is to simplify and shorten this code to be left with a one line condition, I have already tried this technique (Check variable equality against a list of values) with if(["brad","miranda","john"].indexOf(array) > -1) { // .. } but this does not solve my problem. Would you have any idea?
Thanks in advance.
You could use Array#every in combination with Array#includes.
var array = ["miranda", "brad", "johnny"],
needed = ["brad", "miranda", "john"];
console.log(array.every(s => needed.includes(s)));
let array = ["miranda","brad","johnny"]
array.forEach(item =>
console.log(["brad", "miranda", "john"].includes(item) ? "success" : "fail")
);
The answer above covers the solution but you just need to use Array#some instead of Array#every -
var array = ["miranda", "brad", "johnny"],
needed = ["brad", "miranda", "john"];
console.log(array.some(s => needed.includes(s)));

In an array, how to make sure the elements don't repeat, in javascript? [duplicate]

This question already has answers here:
Remove duplicate values from JS array [duplicate]
(54 answers)
Closed 4 years ago.
I have this code, where the point is to read lottery numbers, and the numbers can not be smaller than 0, nor bigger than 49, nor can they repeat themselves. I don't understand how to put that in the while loop. How can I compare each number is inserted with the numbers previously inserted?
var totoloto=new Array(1);
for(var i=0; i<1; i++) {
totoloto[i]=new Array(5);
for(var j=0; j<5; j++) {
do {
totoloto[i][j] = parseInt(readLine("totoloto="));
} while (totoloto[i][j] < 1 || totoloto[i][j] > 49);
}
print(totoloto[i].toString().replaceAll(",", " "));
}
You can use Set instead of Array and just add values into set. If you don't know, Set contains only unique values.
Another way to do this is just using object:
let obj={}
obj.value1 = true // true is just for example. It doesn't make any sense
obj.value2 = true
// After getting all the keys you can
Object.keys(obj) // it returns all the keys in objecti i.e. your values
So, adding values with the same keys has no effect, because object can have only unique keys.

Create strings using .reduce() in Javascript [duplicate]

This question already has answers here:
Algorithm to return all combinations of k elements from n
(77 answers)
Closed 7 years ago.
I need to be able to take a list of strings, and come up with a list of all possible combinations of those strings combined.
["asdf", "ghj","ew","ptum"]
It should get a list something like this, up to n
["agep", "aget", "ageu", ... "fjwm"]
What would I do to get these?
What you are asking is relatively trivial... some for loops can do this fairly easily. Below is one such method you could use.
var input = ["asdf", "ghj", "ew", "ptum"];
function combinations(r, n) {
var o = [];
if (r.constructor.name === "String")
r = r.split("");
if (n.constructor.name === "String")
n = n.split("");
r.forEach(function(i) {
n.forEach(function(j) {
o.push(i + j);
})
})
return o;
}
document.write("<pre>"+JSON.stringify(input.reduce(combinations),null,2)+"</pre>");
You can create an array of letters from the list of strings , like in your case ->
list of strings :
list = ["asdf", "ghj","ew","ptum"]
array of letters would be :-
arr = ["a","s",...,"m"]
then iterate through the array, for each letter make combination with other letters in array ...
the logic will be like this...
//for strings of length 3 ..
for(i in arr){
for(j in arr){
for(k in arr){
if(i!=j && j!=k)
result=i+j+k
}
}
}
p.s I am not into JS , I just told one logic to do this , you can now implent the logic in your language.

Checking length of dictionary object [duplicate]

This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 3 years ago.
I'm trying to check the length here. Tried count. Is there something I'm missing?
var dNames = {};
dNames = GetAllNames();
for (var i = 0, l = dName.length; i < l; i++)
{
alert("Name: " + dName[i].name);
}
dNames holds name/value pairs. I know that dNames has values in that object but it's still completely skipping over that and when I alert out even dName.length obviously that's not how to do this...so not sure. Looked it up on the web. Could not find anything on this.
What I do is use Object.keys() to return a list of all the keys and then get the length of that
Object.keys(dictionary).length
var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
if (c.hasOwnProperty(i)) count++;
}
alert(count);
This question is confusing. A regular object, {} doesn't have a length property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).
Meaning, you have to get the "length" by a for..in statement on the object, since length is not set, and increment a counter.
I'm confused as to why you need the length. Are you manually setting 0 on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?
Edit #1: Why can't you just do this?
list = [ {name:'john'}, {name:'bob'} ];
Then iterate over list? The length is already set.
Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}

Categories

Resources