Compare multiple possible values of an array [duplicate] - javascript

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)));

Related

How do I filter through an array of arrays using an index in JavaScript? [duplicate]

This question already has an answer here:
javascript filter multidimensional array
(1 answer)
Closed 1 year ago.
Im'm working on a JavaScript side prokect and I've got a json file with an array with arrays like this:
arr =
{
"values": [
["Form Factor", "OS"],
["Landscape", "Android 9\n(Source)"],
["Portrait", "Analogue OS"],
["Micro\nLandscape", "?"]
]
}
The first array with "Form factor" (index 0) are the headlines. If I want to get all the "form factors" from the arrays how would I do that?
I know that "Form Factor" has index 0 but how do i filter through several arrays at once with an index? in the end I want an array like
results = ["Form Factor", "Landscape", "Portrait", "Micro\nLandscape"]
I tried it like this:
const index = 0;
const result = this.arr.values.filter(function (eachElem) {
return eachElem == index;
});
But that just gives me back an empty array.
Don't forget to check this
arr.values.map(x => x[0])
Your code isn't working because a) index isn't defined, you need to also put it as a parameter and b) in your case no element will be true.
I would use a traditional for loop in your case but surely if you want you can do it with es6 magic.
let result = [];
for (let i = 0; i < arr.values.length; i++) {
result.push(arr.values[i][0]);
}
console.log(result);
Just use array.find() it's much easier and you can search for your element in your array:
const found = array1.find(element => element > 10);

.map() is storing unwanted undefined values into new array [duplicate]

This question already has answers here:
Why does JavaScript map function return undefined?
(13 answers)
Closed 3 years ago.
Simple array declaration:
let sodas = ["Sprite", "Coke", "Mountain Dew", "Dr. Pepper", "Sunkist"];
I want to use .map() function to create a new array containing sodas only owned by the CocaCola Company, and then display this new array in the console -
let cocacola_sodas = sodas.map(soda => {
if ((soda == "Coke") || (soda == "Sprite")) {
return soda;
}
})
console.log(cocacola_sodas);
This code seems to work, though I'm not sure why it is returning 5 new elements into cocacola_sodas array when only 2 of them should be returned (coke and sprite). The array will display ["Sprite", "Coke", undefined, undefined, undefined]. Why is it returning undefined values?
#awoldt, to help you understand what is actually happening, Array.prototype.map will always return the same number of elements from the input array to a new array.
so best way to think about it is you give map an array with x elements, regardless of what you do to those elements inside the block you pass to map, it will always return X # of elements in the new array.
As was suggested, something like filter/reduce will return a new array with just the elements that meet the criteria you set out int he block passed to those helpers
you can read more about map and all the Array.prototype.methods at MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Use filter instead of map. It was made or use in situations like this. As pointed by other answers map will always return the same number of elements as present in the input array
let sodas = ["Sprite", "Coke", "Mountain Dew", "Dr. Pepper", "Sunkist"];
let cocacola_sodas = sodas.filter(soda => {
if ((soda == "Coke") || (soda == "Sprite")) {
return soda;
}
})
console.log(cocacola_sodas);
To elaborate on #ellipsis answer:
The reason filter is better here is because it is generating a new array of items not filtered out of the original array.
The reason map is giving you the results you see are because it's not filtering, but changing each element and giving it to the result array. I think a code example would help to clarify.
Map might look something like this under the hood:
var array = ['one', 'two', three];
var mapFunc = function(item) {
if(item == 'two')
return item;
};
var mappedArray = [];
for(var i = 0; i < array.length; i++)
mappedArray.push(mapFunc(array[i]));
Obviously the above is simplified to be clear, but as you can see the mapped array will have as many items in it as the original array. Since you return nothing in the case item doesn't equal two then you return undefined hence why you have the extra items in your example.
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
let sodas = ["Sprite", "Coke", "Mountain Dew", "Dr. Pepper", "Sunkist"];
let cocaCola = ["Coke","Sprite"];
let cocacola_sodas = sodas.filter(soda => cocaCola.includes(soda))
console.log(cocacola_sodas);

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.

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

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. :)

removing elements from an array from another array in javascript [duplicate]

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 8 years ago.
Hi i need to remove the array from another array.Below is the code that i had tried
var dummyObj = ["item1"];
var dummyArray = [ "item1", "item3", "item2"];
var data1=removeFromArray(dummyArray, dummyObj);
console.log("data1"+data1)
function removeFromArray(array, item)
{
while((index = array.indexOf(item)) > -1)
array.splice(index,1);
return array
}
below is my output
item1,item3,item2
But the required output is
item3,item2
Dont know where i am going wrong.Any help regarding this will be much helpful
You argument item is an is an array object so you have to use it like item[0]
while((index = array.indexOf(item[0])) > -1)
if dummyObj contains for than one values then you have to add an extra loop
function removeFromArray(array, item)
{
for(var j=0;j<item.length;j++){
while((index = array.indexOf(item[j])) > -1)
array.splice(index,1);
}
return array
}
The problem with your code is that, item is actually dummyObj which is an array and that does not exist in dummyArray. That is why it fails to remove it.
You can use Array.prototype.filter, like this
dummyArray = dummyArray.filter(function(currentItem) {
return dummyObj.indexOf(currentItem) === -1;
});
console.log(dummyArray); // [ 'item3', 'item2' ]
Check out Underscore.js, a javascript utility belt:
http://underscorejs.org/#difference
You have few errors there:
while((index = array.indexOf(item)) > -1)
Should be
while((index = array.indexOf(item) > -1)
Also you need to loop through both dummyArray and dummyObj, because your item variable is actually dummyObj, so you need to loop through it to check each element separately.

Categories

Resources