how do I check multiple values in an object? - javascript

So for example you select up to 3 elements. Every time when you select an element it is stored in a array. Select a and var objects = ["a"]; after that you select b and var objects = ["a", "b"];
Now my code is working without looking for objects in array but I would like to make it working like this.
So what is doing now it gets option element and look for it in arrays. But every time when you select a new option I want to squeeze the list of searching. So if at first point it was looking only for a option in all possibilities now it will look for a and b where it could be {["a","b","c"]} or {["a","c","b"]} or {["c","b","a"]} etc.
var filtered = s.Data.results.filter(function (el) {return el.result.indexOf(option) > -1});

You could filter the results array with a check for every element of options, if it is in the inner array of results.
var results = [["a", "c", "b"], ["a", "c", "b"], ["b", "c", "d"], ["b", "c", "e"]],
option = ["a", "b"],
filtered = results.filter(function (a) {
return option.every(function (b) {
return a.indexOf(b) !== -1;
});
});
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }

I'm not entirely sure what you're asking, but it sounds like you want to filter your results array by a collection of options? Something like this:
var options = ["a", "b"];
var results = ["c", "b", "a"];
var filtered = results.filter(result => options.indexOf(result) !== -1);

You will need to reduce the list of options to remove the items you don't want. I didn't
reducedOptions = s.Data.results.reduce((acc, curr) => {
if (el.result.indexOf(curr) > -1) {
acc.push(curr)
}
return acc;
}, [])
Also lodash has something built in for this called without
https://lodash.com/docs/4.17.4#without

Related

Generate all possible combinations of variable-length comma-space-separated strings in JavaScript

Input:
["A", "B", "C"]
Expected output:
["A", "B", "C", "A, B", "A, C", "B, C", "A, B, C"]
This is a simple example case, but the function should work for strings and arrays of all lengths. Strings may have certain letters repeated, e.g. "AABB", which is distinct from "A" and "B". Order by number of elements first then alphanumerical sort is desired but not required for this solution.
You can use a permutation function, and then join certain strings after spliting them:
const arr = ["A", "B", "C"];
function getCombinations(chars) {
var result = [];
var f = function(prefix, chars) {
for (var i = 0; i < chars.length; i++) {
result.push(prefix + chars[i]);
f(prefix + chars[i], chars.slice(i + 1));
}
}
f('', chars);
return result;
}
const permutations = getCombinations(arr).map(e => e.length > 1 ? e.split("").join(", ") : e);
console.log(permutations);
Permutations function from this answer.
This is actually something I have been working on in scheme lately, what you appear to be looking for is a procedure that generates a power set from a set input. There just happens to be a recursive algorithm that already exists to solve this problem, but it is based on math that I don't need to go into here.
Here is a simple JavaScript implementation from another post here that I modified for your problem:
const myList = ["A", "B", "C"];
const powerSet =
theArray => theArray.reduce(
(subsets, value) => subsets.concat(
subsets.map(set => [value,...set])
),
[[]]
);
console.log(powerSet(myList));
This is what I ended up using as a basis for my implementation:
https://www.w3resource.com/javascript-exercises/javascript-function-exercise-21.php

javascript - check if array contains any of another array of strings

strings_to_check = ["a", "b", "c"]
test_arrrays = [ [ "a", "c", "e", "g"], [ "v", "x", "y", "z"] ]
What is the right way to check if each array in test_arrays contains any of the strings in strings_to_check array - ie. a, b or c
I could do the following, but it has its downside that even if one of the strings is present, it still check's for the rest.
for(let i = 0; i < test_arrrays.length; i++){
for(let j = 0; j < strings_to_check.length; j++){
if(test_arrrays[i].indexOf(strings_to_check[j]) > -1) {
console.log("matched");
}
}
}
This can be much more simply done with higher order functions, instead of devolving to using for loops and a slew of indices.
We want to see if all test_arrrays elements meet some criteria, so we know we should use every:
test_arrrays.every(/* some criteria */);
Now we just have to find out what that criteria is. "contains any of the strings in strings_to_check" Sounds like we need to use some on test_array, to find out if any of its strings are contained in strings_to_check. So our "criteria" will be:
test_arrray => test_arrray.some(s => strings_to_check_set.includes(s))
putting it together, we get:
test_arrrays.every( test_arrray =>
test_arrray.some(s => strings_to_check_set.includes(s))
)
includes has linear time complexity, so we can improve this algorithm by using a Set, and replacing includes with has, which has constant time complexity., to obtain this final result:
strings_to_check = ["a", "b", "c"]
test_arrrays = [ [ "a", "c", "e", "g"], [ "v", "x", "y", "z"] ]
strings_to_check_set = new Set(strings_to_check)
test_arrrays.every(test_arrray =>
test_arrray.some(s => strings_to_check_set.has(s))
)
Assuming that you want to check if every array from test_arrays contains at least one element from the strings_to_check array, you could use mix of Array#every and Array#some functions.
var strings_to_check = ["a", "b", "c"],
test_arrrays = [ [ "a", "c", "e", "g"], [ "v", "x", "y", "z"] ],
res = test_arrrays.every(v => v.some(c => strings_to_check.indexOf(c) > -1));
console.log(res);
If you have multiple test_arrrays, it makes sense to convert the strings_to_check into a Set for constant time lookup. The overall time complexity then reduces from O(m n) to O(m + n log n) where n is the number of elements in strings_to_check and m is the total number of elements in all test_arrrays and O(n log n) is the Set setup time.
A generic check function would then look as follows:
// Check if each haystack contains at least one needle:
function check(needles, haystacks) {
needles = new Set(needles);
return haystacks.every(haystack => haystack.some(element => needles.has(element)));
}
// Example:
console.log(check(
["a", "b", "c"],
[["a", "c", "e", "g"], ["v", "x", "y", "z"]]
));
If you only need to match one string just add break just like this :
for(/*loop settings*/){
/*some code*/
for(/*loop settings*/){
/*some code*/
if(/*some conditional statement*/){
/*handling stuff*/
break;
}
}
}

How to double array values

I have an array:
arr = ["a", "b", c"]
I want to double values like
arr = ["a", "b", c", "a", "b", "c"]
(not in particular order).
What's the best way to do it in JavaScript?
Possible solution, using Array#concat.
var arr = ["a", "b", "c"],
res = arr.concat(arr);
console.log(res);
You could also use ES6 spread syntax with Array.push:
let arr = ['a', 'b', 'c'];
arr.push(...arr);
console.log(arr);
You can use Array() constructor and inside specify number of times you want to repeat array and then use fill() and spread syntax to create one array.
var arr = ["a", "b", "c"];
var newArr = [].concat(...Array(3).fill(arr))
console.log(newArr)
A for-loop solution which mutates the array itself.
var arr=["a","b","c"];
var len=arr.length;
for(var i=len;i<2*len;i++) arr[i]=arr[i-len]
console.log(arr);

Generating 3D array from 2D array

I'm trying to create a music game where I have to generate a 3D array from a basic 2D array. The plan was to copy and paste the 2D array 4 times into the 3D array before modifying it, as shown:
var note3base = [
["C", "E", "G"],
["C#", "E#", "G#"],
["Db", "F", "Ab"],
["D", "F#", "A"],
["Eb", "G", "Bb"],
["E", "G#", "B"],
["F", "A", "C"],
["F#", "A#", "C#"],
["Gb", "Bb", "Db"],
["G", "B", "D"],
["Ab", "C", "Eb"],
["A", "C#", "E"],
["Bb", "D", "F"],
["B", "D#", "F#"],
["Cb", "Eb", "Gb"]
];
var note3 = new Array(4);
for (h=0;h<note3.length;h++){
note3[h] = note3base;
} //creates 4 copies of note3base in a 3d-array to be modified
for (i=0;i<note3[0].length;i++){
note3[1][i][1] = flat(note3[1][i][1]); //minor
note3[2][i][1] = flat(note3[2][i][1]);
note3[2][i][2] = flat(note3[2][i][2]); //dim
note3[3][i][2] = sharp(note3[3][i][2]); //aug
} //how did everything become the same?
The problem now seems to be that the for loop seems to apply the method to every single array (0 through 3).
The desired output for note3[0][1] would be C E G, note3[1][1] would be C Eb G, note[2][1] would be C Eb Gb, note[3][1] would be C E G#.
Any help is greatly appreciated!
I've included the (working) sharp and flat methods below for reference:
function sharp(note){
var newnote;
if (note.charAt(1) == "#"){
newnote = note.replace("#", "x");
} else if (note.charAt(1) == "b"){
newnote = note.replace("b", "");
} else {
newnote = note + "#";
}
return newnote;
}
function flat(note){
var newnote;
if (note.charAt(1) == "#"){
newnote = note.replace("#", "");
} else {
newnote = note + "b";
}
return newnote;
}
The problem is that when you assign a variable equal to an array like this:
someVar = someArray;
...it doesn't make a copy of the array, it creates a second reference to the same array. (This applies to all objects, and arrays are a type of object.) So after your loop, where you've said:
for (h=0;h<note3.length;h++){
note3[h] = note3base;
...all of the elements in note3 refer to the same underlying array.
To make an actual copy, you can manually copy all of the elements across using a loop, or you can use the .slice() method to make a copy for you:
for (h=0;h<note3.length;h++){
note3[h] = note3base.slice();
}
But that will only solve half of the problem, because note3base itself contains references to other arrays, and .slice() will just copy these references. That is, although note3[0] and note3[1] (and 2 and 3) will refer to different arrays, note3[0][0] and note3[1][0] and note3[2][0] and note3[3][0] will refer to the same ["C", "E", "G"] array. (And so forth.)
You need what's called a "deep copy". You could do it with a nested loop:
for (h=0;h<note3.length;h++){
// create this element as a new empty array:
note3[h] = [];
// for each 3-note array in note3base
for (var k = 0; k < note3base.length; k++) {
// make a copy with slice
note3[h][k] = note3base[k].slice();
}
}
Having said all that, I think an easier way to do the whole thing would be instead of having a note3base variable that refers to an array, make it a function that returns a new array:
function makeNote3Array() {
return [
["C", "E", "G"],
["C#", "E#", "G#"],
["Db", "F", "Ab"],
["D", "F#", "A"],
["Eb", "G", "Bb"],
["E", "G#", "B"],
["F", "A", "C"],
["F#", "A#", "C#"],
["Gb", "Bb", "Db"],
["G", "B", "D"],
["Ab", "C", "Eb"],
["A", "C#", "E"],
["Bb", "D", "F"],
["B", "D#", "F#"],
["Cb", "Eb", "Gb"]
];
}
Because the function uses an array literal it will create a brand new array of arrays every time it is called. So then you can do the following, with no need for .slice() or nested loops:
var note3 = new Array(4);
for (h=0;h<note3.length;h++){
note3[h] = makeNote3Array();
}
TL;DR, do this:
for (h=0;h<note3.length;h++){
note3[h] = note3base.slice(0);
}
Explanation:
The problem is coming from the difference between passing something'by value' and 'by reference' in Javascript.
When you assign a primitive value to a variable, like a = "string";, and then assign that to another variable, like b = a;, the value is passed to b 'by-value': its value is assigned to b, but b references a different part of memory. There are now two "string" values in the memory, one for a, and one for b.
a = "string";
b = a;
a = "gnirts";
console.log(b); // "string"
This is not how it works for non-primitive types, such as arrays. Here the value is passed to b 'by reference', meaning that there is still only one [1, 2, 3] array in the memory, and both a and b are pointing at it. This means that is you change an element in a, it will change for b as well, because they reference the same array in memory. So you get this:
a = [1, 2, 3];
b = a;
a[0] = "hello";
console.log(b); // ["hello", 2, 3]
b[0] has changed because it references the same location in memory as a[0]. To get around this problem, we need to explicitly make a copy of note3base when passing it to another variable, rather than just passing it by reference. We can do this with note3base.slice(0) as above.
Edit: read more here

Get the index of element in difference array

I've two arrays
var valid = ["a", "b"];
var different = ["a", "c", "b"];
What is the best way to find out the position of element different? Only one element can be different.
In this case the different array change only by one element and I want the index (1) of different array.
There are multiple ways to do this. For instance, you could iterate over the valid array and when the values don't match up, then you know the index of the different value. In this case, it is 1.
Example Here
var valid = ["a", "b"];
var different = ["a", "c", "b"];
valid.forEach(function (value, i) {
if (value !== different[i]) {
console.log(i); // 1
}
});
Returns the index of the differing value:
var valid = ['a', 'b'];
var different = ['a', 'c', 'b'];
var diffIndex = valid.findIndex(function (value, index) {
return value !== different[index];
});
alert('Array differs at index: ' + diffIndex);
Note that findIndex is part of the ES2015 standard.

Categories