Comparing an array object to string using mocha && chai. - javascript

I am using mocha and chai for the first time and have no idea what is going on? im trying to say that my shuffle method has moved the array objects around and the first array object no longer - "sam1" IE -
describe('Shuffle', function(){
it('Shuffle should randomly move array items by their index', function(){
let group = ["sam1","sam2","sam3","sam4","sam5","sam6","sam7","sam8","sam9"];
let result = shuffle(group);
assert.equal(result, group[0] != "sam1");
});
});
this is the error -
AssertionError: expected [ Array(9) ] to equal true
how do i compare the two to make it true? or is there a better way to show the array has been shuffled?

The first argument of assert.equal() is where your comparison should be,
so
assert.equal(result, group[0] != "sam1");
should be
assert.equal(comparison, 'message to display on failure');
and a better way to know if the array has been shuffled would be to compare every element in the result with the original array, so something like
for(int i = 0; i < group.length; i++) {
if (group[i] !== result[i]) {
return false;
}
}
although, depending on how you shuffle there is a chance it shuffles in to the same order.
see http://www.chaijs.com/api/assert/ for more details on assert

It looks like shuffle returns an array. So to check if your first element in result array is not the same as in group array you have to compare the first two elements of arrays. If you want to use assert method, you have to do it this way:
assert(result[0] != group[0], "string if the test fails");
Just at the top of this doc

The easy way is to compare the previous array and after array. Don't use equal here but instead deepEqual to compare array or object.
it('Shuffle should randomly move array items by their index', function(){
let group = ["sam1","sam2","sam3","sam4","sam5","sam6","sam7","sam8","sam9"];
let result = shuffle(group);
assert.deepEqual(result, group);
});
});
Ref: http://www.chaijs.com/api/assert/#method_deepequal

Something like this?
assert.notEqual(group[0], "sam1");
You can find the list of usable functions here
http://www.chaijs.com/api/assert/

expect(result).to.have.members(group); // to check if all members there - doesn't care about the order
expect(result).to.not.eql(group); // to check if order has changed - there's a catch though; only 1 change on order (e.g. `shuffle` swapped **just** 2 members) is sufficient to this assertion to pass
Sources;
https://medium.com/building-ibotta/testing-arrays-and-objects-with-chai-js-4b372310fe6d
https://www.chaijs.com/api/bdd/#method_members
https://www.chaijs.com/api/bdd/#method_eql

Related

Confusion with how indexOf works in JS

I am new to JS and was trying to learn how to properly work with indexOf in JS, that is, if you look at the code below:
var sandwiches = ['turkey', 'ham', 'turkey', 'tuna', 'pb&j', 'ham', 'turkey', 'tuna'];
var deduped = sandwiches.filter(function (sandwich, index) {
return sandwiches.indexOf(sandwich) === index;
});
// Logs ["turkey", "ham", "tuna", "pb&j"]
console.log(deduped);
I am trying to remove duplicates but wanted to ask two questions. Firstly, in here return sandwiches.indexOf(sandwich) === index; why we need to use "== index;". Secondly, since indexOf returns index like 0, 1 or 2 ... then why when we console.log(deduped) we get array of names instead of array of indexes. Hope you got my points
You use a method of Javascript Array that is filter, this method take a function that returns a boolean.
The function filter returns a new Array based on the function passed applied to each entry.
If the function return true, then the entry is included in the new Array, otherwise is discarded.
As the functions check the indexOf an entry to be the current index is true for the first occurrency of the entry.
All the duplications will fail the expression as they are not the first index found by indexOf, so they are discarded.
since the logic is to remove the duplicates from the array,
in your example, you have "turkey" as duplicates.
the "turkey" exists in position 0,2,6
so whenever you call indexOf("turkey") always returns 0 because the indexOf function returns the first occurrence of a substring.
so for the elements in position 2 & 6 the condition fails. then it won't return that element.
That is how the filter works in javascript. it evaluates the condition and returns true or false that indicates whether an element to be included in the new array or not, in your example the condition is return sandwiches.indexOf(sandwich) === index;
Perhaps the basic logic is easier to see at a glance if you use arrow notation:
const deduped = myArray => myArray.filter((x, i) => myArray.indexOf(x) === i);
The key point is that indexOf returns the index of the first occurrence of x. For that occurrence the result of the comparison will be true hence the element will be retained by the filter. For any subsequent occurrence the comparison will be false and the filter will reject it.
Difference between === (identity) and == (equality): if type of compared values are different then === will return false, while == will try to convert values to the same type. So, in cases where you compare some values with known types it is better to use ===. (http://www.c-point.com/javascript_tutorial/jsgrpComparison.htm)
You get as result an array of names instead of array of indexes because Array.filter do not change the values, but only filter them. The filter function in your case is return sandwiches.indexOf(sandwich) === index; which return true or false. If you want get the indexes of your items after deduplication, then use map after filter:
a.filter(...).map(function(item, idx) {return idx;})
#Dikens, indexOf gives the index of the element if found. And if the element is not found then it returns -1.
In your case you are filtering the array and storing the values in the deduped. That's why it is showing an array.
If you console the indexOf in the filter function then it will log the index of the element.
For example :
var deduped = sandwiches.filter(function (sandwich, index) {
console.log(sandwiches.indexOf(sandwich));
return sandwiches.indexOf(sandwich) === index;
});

When to use forEach vs map when I am just iterating over something?

I know that map returns a new array, and that forEach does not return anything (the docs say it returns undefined).
For example, if I had some code like this:
let test;
values.forEach((value, idx) => {
if (someNumber >= value) {
test = value;
}
});
Here I am just checking if someNumber is greater than some value, and if it is then set test = value. Is there another array method I should use here?
Or is it fine to use .forEach
Your example doesn't make sense because it finds the last value that is less than or equal to someNumber, repeatedly assigning to the test variable if more than one is found. Thus, your code is not truly expressing your intent well since other developers can be confused about what you're trying to achieve. In fact, other answers here have had differing opinions on your goal due to this ambiguity. You even said:
if the number is great than or equal to the value from the array at whatever index, stop, and set test equal to that value
But your code doesn't stop at the first value! It keeps going through the entire array and the result in test will be the last value, not the first one.
In general, making your loop refer to outside variables is not the best way to express your intent. It makes it harder for the reader to understand what you're doing. It's better if the function you use returns a value so that it's clear the variable is being assigned.
Here's a guide for you:
forEach
Use this when you want to iterate over all the values in order to do something with each of them. Don't use this if you are creating a new output value--but do use it if you need to modify existing items or run a method on each one, where the forEach has no logical output value. array.forEach at MDN says:
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a Boolean return value, you can use every() or some() instead. If available, the new methods find() or findIndex() can be used for early termination upon true predicates as well.
find
Use this when you want to find the first instance of something, and stop. What you said makes it sound like you want this:
let testResult = values.find(value => value <= someNumber);
This is far superior to setting the test value from inside the lambda or a loop. I also think that reversing the inequality and the variables is better because of the way we tend to think about lambdas.
some
These only give you a Boolean as a result, so you have to misuse them slightly to get an output value. It will traverse the array until the condition is true or the traversal is complete, but you have to do something a bit hacky to get any array value out. Instead, use find as above, which is intended to output the found value instead of simply a true/false whether the condition is met by any element in the array.
every
This is similar to some in that it returns a Boolean, but is what you would expect, it is only true if all the items in the array meet the condition. It will traverse the array until the condition is false or the traversal is complete. Again, don't misuse it by throwing away the Boolean result and setting a variable to a value. If you want to do something to every item in an array and return a single value, at that point you would want to use reduce. Also, notice that !arr.every(lambdacondition) is the same as arr.some(!lambdacondition).
reduce
The way your code is actually written—finding the last value that matches the condition—naturally lends itself to reduce:
let testResult = values.reduce(
(recent, value) => {
if (value <= someNumber) {
recent = value;
}
return recent;
},
undefined
);
This does the same job of finding the last value as your example code does.
map
map is for when you want to transform each element of an array into a new array of the same length. If you have any experience with C# it is much like the Linq-to-objects .Select method. For example:
let inputs = [ 1, 2, 3, 4];
let doubleInputs = inputs.map(value => value * 2);
// result: [ 2, 4, 6, 8]
New requirements
Given your new description of finding the adjacent values in a sorted array between which some value can be found, consider this code:
let sortedBoundaries = [ 10, 20, 30, 40, 50 ];
let inputValue = 37;
let interval = sortedBoundaries
.map((value, index) => ({ prev: value, next: sortedBoundaries[index + 1] }))
.find(pair => pair.prev < inputValue && inputValue <= pair.next);
// result: { prev: 20, next: 30 }
You can improve this to work on the ends so that a number > 50 or <= 10 will be found as well (for example, { prev: undefined, next: 10 }).
Final notes
By using this coding style of returning a value instead of modifying an outside variable, you not only communicate your intent better to other developers, you then get the chance to use const instead of let if the variable will not be reassigned afterward.
I encourage you to browse the documentation of the various Array prototype functions at MDN—doing this will help you sort them out. Note that each method I listed is a link to the MDN documentation.
I would suggest you to use Array#some, instead of Array#forEach.
Array#forEach keeps iterating the array even if given condition was fulfilled.
Array#some stops iteration when given condition was fulfilled.
One of the advantages would be connected with performance, another - depends on your purposes - Array#forEach keeps overwriting the result with every passed condition, Array#some assigns the first found value and stops the iteration.
let test,
values = [4,5,6,7],
someNumber = 5;
values.some((value, idx) => {
if (someNumber >= value) {
test = value;
return test;
}
});
console.log(test);
Another option would be to use the Array.some() method.
let test;
const someNumber = 10;
[1, 5, 10, 15].some(function (value) {
if (value > someNumber) {
return test = value
}
})
One advantage to the .some() method over your original solution is optimization, as it will return once the condition has been met.
How about Object?
you can search with for-of

How to get all children of a subArray in Javascript

So here's my problem:
So this is what my array looks like, I have shown a fragment of it here (from the console window).
It's overall pretty basic right? Except for it's indexing. As you see the first has value "1" and let's say the second has value "4". As for it's subarrays, these have custom indexes too.
Therefore, the old fashioned:
for(i=0; i<array.length; i++){
someVar = array[i];
//do something
}
won't work.
I get the 1 or 4 from iterating through another array, so don't need to get those.
I want to get all subArrays(not the further nested subArrays, only the second level).
So basicly what I want is something like this(is there something like this?):
array[someIndex].children.forEach(
//do something with **this**
)
To make it more practical for you:
So I know that the first array has index 1. How can I get the values of cat1 and cat2 without knowing it has index 2 (this could also be 6 or 42 for example). In this case, the first array only has one subArray but I would like to make it work for multiple subArrays. (to clarify, select cat1, cat2 from the second level subarray with, in this case, index 2)
Thanks in advance, any help is appreciated!
Evoc
Those aren't arrays. You have
[ { "1": { etc...
which is an array containing an object containing multiple other objects. You can't really use a for(i=...) loop for this, because your keys aren't sequential. You should use a for ... in loop instead:
arr = [{"1":{....}}];
for (i in arr[0]) {
for (j in arr[0][i]) {
console.log(arr[0][i][j]['msg']);
}
}
Use Object.getOwnPropertyNames to get the properties ordered with the integer indices first, from smallest to greatest. Iterate them to get msg1.
var array = {"1":{"3":{"5":{"data":"someData","moreData":"someMoreData"},"msg1":"hello world","msg2":"foo equals bar"},"5":{"8":{"data":"someData","moreData":"someMoreData"},"msg1":"world hello","msg2":"bar equals foo"},"your_name":"jimmy","your_msg":"hello world"},"4":{"3":{"5":{"data":"someData","moreData":"someMoreData"},"msg1":"hello world","msg2":"foo equals bar"},"5":{"8":{"data":"someData","moreData":"someMoreData"},"msg1":"world hello","msg2":"bar equals foo"},"your_name":"billy","your_msg":"foo equals bar"}};
for(let key of Object.getOwnPropertyNames(array[1])) {
if(Object(array[1][key]) !== array[1][key]) break;
console.log('msg1 of "'+key+'": ' + array[1][key].msg1);
}
console.log('your_msg: ' + array[1].your_msg);
The example you showed it's an array with only one index, inside of this index there are nested objects, you could iterate them using the property iterator (foreach). You have to go to the second level tho, since the values you need are there.
for (var key in object) {
for(var anotherKey in object[key]) {
//check for undefined
if(object[key][anotherKey].hasOwnProperty('msg')) {
//code
}
}
}
{ } - declaring objects (literal)
[ ] - declaring arrays

How to compare two objects

I have a scenario, where I have two different Objects.
Scenario to achieve:
From two objects I need to match the values which has "A1","B2", etc...
Since both the objects values are not in proper order, the loop is breaking and missing some values.
In my demo the object1 has same repeated value i.e. "C3", It should be displayed only once.
Final output required is I need to detect only the matched values from two objects and display its corresponding "a" and "b values."
I have tried almost 90%, but somewhere some minor error is breaking my loop, Please help me out.
Sample code:
for(var i=0;i<obj1.results[0].loc.length;i++){
var findA = obj1.results[0].loc[i].anc[0].title;
for(var j=0;j< obj2.ILoc.length;j++){
var findB = obj2.ILoc[j].ais;
if(findA == findB) {
var a = obj1.results[0].loc[i].a;
var b = obj1.results[0].loc[i].b;
console.log(a);
console.log(b);
}
}
}
This is what I have tried:
Demo Link
I would recommend using for...in loop, since you're using objects instead of arrays.
for (variable in object) {...
}
If length property of both objects is equal, then this kind of loop alone will help you to compare objects with ease.
I would recommend using the diff module. You can use it in node.js and the browser.

How to change array push to a particular array?

I want to add only integers and ignore others in a particular array. I want to add this condition on that array's push event.
Array.prototype.push = function(){
if(condition){
//execute push if true
}
else
{
//return false
}
}
Help me how to code this? This affects all the array in my code. I want to check this condition on push only for a particular array. what are the ways to achieve it?
jsFiddle: http://jsfiddle.net/QhJzE/4
Add the method directly to the array:
var nums = [];
nums.push = function(n) {
if (isInt(n))
Array.prototype.push.call(this, n);
}
nums.push(2);
nums.push(3.14);
nums.push('dawg');
console.log(nums);
(See How do I check that a number is float or integer? for isInt function.)
Here's some great information: http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/. What I've shown here is called "direct extension" in that article.

Categories

Resources