Im working in a class and the built in editor is telling me this funtion returns "a", but i expected it to return "a","b","c","d". Can someone please explain what im not understanding here ?
function chunk(arr) {
for(var i = 0; i <= arr.length; i++)
return arr[i];
}
chunk(['a', 'b', 'c', 'd']);``
A function can only have one return value, so the code ends when the return is executed the first time. The return statement is defined to exit the function immediately.
The return value can however be an array (or an object), so if you want to return multiple values you can put them in an array:
function chunk(arr) {
var result = [];
for(var i = 0; i <= arr.length; i++) {
result.push(arr[i] + '!');
}
return result;
}
var values = chunk(['a', 'b', 'c', 'd']);
// values now contain ['a!', 'b!', 'c!', 'd!']
You are returning too early:
function chunk(arr) {
var newArr = [];
for(var i = 0; i <= arr.length; i++) {
newArr.push(arr[i]);
}
return newArr;
}
This should work.
It returns 'a' because the return statement itself is returning a specific item in the array
return arr[i];//in example above, i is 0
^^^
Imagine the array structured like
0 -> a
1 -> b
2 -> c
3 -> d
4 -> e
So, when you access with index 0, a is returned.
To return the whole array, do so without index
return arr;
You should use .map() method, which creates a new array with the results of calling a provided function on every element in this array.
It's more clean.
So just do :
function chunk(arr) {
//Map our array and return a new array
return arr.map(function(elm){
return elm;
});
};
var a = chunk(['a', 'b', 'c', 'd']);
console.log(a);
//Print ["a", "b", "c", "d"]
Related
I have a function that accepts an array as the parameters, the function should console.log the array elements into a single array. But what I have is that the array element is printed into separate arrays. My code below
const result = []
function DNAStrand(dna){
//your code here
for (let i = 0; i < dna.length; i++) {
const element = dna[i];
console.log(new Array(element))
}
}
DNAStrand("AAAA") \\ is printing ['A'], ['A'], ['A'], ['A']
\\ Instead of ['A', 'A', 'A', 'A']
You need to create an Array object first then insert the value in loop and finally do a Console.log after end of the loop.
const result = []
function DNAStrand(dna) {
//your code here
let arr = [];
for (let i = 0; i < dna.length; i++) {
const element = dna[i];
arr[i] = element;
}
console.log(arr)
}
DNAStrand("AAAA");
You shouldn't iterate through array, instead you can use Array.from() or .split('')
function DNAStrand(dna){
console.log(Array.from(dna))
}
DNAStrand("AAAA")
or
function DNAStrand(dna){
console.log(dna.split(''))
}
DNAStrand("AAAA")
I got this task and I can't get how to replace the matches with the string "BUSTED", can you help me please. I'm new to JS. Most probably there is a way more elegant way to do this. Any help appreciated.
You're given two arrays: one that holds every member of fCommunity and another one
that holds every possible suspect.
Replace every fCommunity member from the Suspect list with the word "BUSTED"
var fCommunityMembers = ['A','B','C'];
var SuspectList = ['F','X','B','Z','Y','C','ZS','D','K','M','N'];
I managed to retrieve the matching members but how do I replace them in the suspect list?:
Array.prototype.diff = function(SuspectList) {
var ret = [];
this.sort();
SuspectList.sort();
for(var i = 0; i < this.length; i += 1) {
if(SuspectList.indexOf( this[i] ) > -1){
ret.push( this[i] );
}
}
return ret;
};
var ListOfMatches = Array.from(fCommunityMembers.diff(SuspectList));
console.log( ListOfMatches );
Use Array.prototype.map() to iterate fCommunityMembers. If an member is found in the SuspectList return BUSTED, if not return the member:
var fCommunityMembers = ['A','B','C'];
var SuspectList = ['F','X','B','Z','Y','C','ZS','D','K','M','N'];
var result = fCommunityMembers.map(function(member) {
return SuspectList.indexOf(member) !== -1 ? 'BUSTED' : member;
});
console.log(result);
What you need is a function that can do the intersection between two arrays
filter can help in your case
var fCommunityMembers = [
'A',
'B',
'C',
'D',
'F'
];
var SuspectList = [
'F',
'X',
'B',
'Z',
'Y',
'C',
'ZS',
'D',
'L'
];
var suspects= fCommunityMembers.filter(function(el){
return SuspectList.indexOf(el)>-1;
});
Edit #1
To replace the values by busted, do the following:
var suspectsFnc = function (fc, sus) {
var busted = fCommunityMembers.filter(function (el) {
return SuspectList.indexOf(el) > -1;
});
for (var i = 0; i < fc.length; i++) {
if (busted.indexOf(fc[i]) > -1) {
fc[i] = "Busted";
}
}
return fc;
}
var suspects = suspectsFnc(fCommunityMembers, SuspectList);
Judt use filter like this :
var ListOfMatches = SuspectList.filter(x => fCommunityMembers.indexOf(x) !== -1);
and a forEach loop to insert BUSTED instead of previous matched elements
fCommunityMembers.forEach((x,i,arr) => {
if (SuspectList.indexOf(x) !== -1)
arr[i] = "BUSTED";
});
How can I check the array has empty element or not?
Imagine this array,
var arr = [ 'a', 'b', , 'd'];
the arr[2] is undefined. I want to check this. If the element has empty element, return 'true' or return false. Maybe like this,
function hasEmptyElement(array){
for (var i=0; i<array.length; i++){
if (typeof arr[i] == 'undefined'){
return true;
// and then ?
// should I use double for loop or helper variable?
}
}
}
I confuse how can I do this. Please help me the clevers.
As of ES2016, you should use Array.prototype.includes:
const array = ["a", "b", , "d"];
array.includes(undefined); // true
(You don't need to write undefined, but this makes it more clear what's happening.)
Note that this method treats slots valued undefined and empty slots the same, although they're not. If you need to differentiate these two cases as well, starting from ES2017, you can use Object.values making the following expression true if there are empty slots in the array:
Object.values(array).length !== array.length; // true
First, note the difference between empty slots and slots with undefined value:
var arr = [/*empty slot*/, undefined];
Object.keys(arr); // ["1"] but not "0"
"0" in arr; // false
"1" in arr; // true
ES5 array methods skip empty slots. ES6 [].includes does not.
That means you can use
arr.includes(undefined); // has empty slot OR contains undefined value
arr.indexOf(undefined) > -1; // contains undefined value
If you want to test only if there are empty slots, you can iterate manually with a for loop and check whether all indices between 0 and the length of the array are present, e.g. with in operator.
(function() {
for(var i=0; i<arr.length; ++i) if(!(i in arr)) return true;
return false;
})(); // has empty slot
Or you can also use ES5 array methods and check if they skipped an index.
var n = 0;
arr.some((_,i) => i !== n++); // has empty slot
You can do something like that:
function hasEmptyElement(array){
for (var i=0; i<array.length; i++){
if (!(i in array)) {
return true;
}
}
return false;
}
The main point of this implementation is that it makes difference between [1,,3] and [1, undefined, 3]
try
var hasAnyEmptyElement = arr.filter(function(val){ return (typeof val) != "undefined" }).length != arr.length;
DEMO
var arr = [1,2];
arr[4] = 2;
var hasAnyEmptyElement = arr.filter(function(val){ return (typeof val) != "undefined" }).length != arr.length;
alert(hasAnyEmptyElement);
You could also use Array.prototype.findIndex()
var arr = ['a', 'b', , 'd'];
document.write(arr.findIndex(e => e === undefined) > -1);
var temp = arr.filter(item => item);
This will give you a new array with below elements:
["a", "b", "d"]
The above solution will help to remove empty as well as null values.
Simple implementation using set
var arr = [ 'a', 'b', , 'd'];
// Using Set from es6
var arraySet = new Set(arr)
arraySet.has(undefined) // returns true
Thanks!
For ES5- you can do
var arr = [ 'a', 'b', , 'd'];
arr.filter(function() { return true }).length === arr.length
That is going to return false if there is a undefined
ES2015 check includes
You can try like this:
var arr = [ 'a', 'b',, 'd'];
function myfunc(arr) {
for(var i=0; i<arr.length; i++) {
if (!(i in arr)) return false;
}
return true;
}
alert( myfunc(arr));
`Check null/undefined values in Array`
function checkNullValue(a) {
if (typeof (a) == 'undefined' || a === null) {
return false;
} else {
return true;
}
}
var arrayMonthVal = ['1','2',,'6','null', '8'];
var pass = arrayMonthVal.some(checkNullValue);
I recently needed to know if a given array element was empty and this page helped me derive the following solution:
/** Determine if an array element is empty.
* #param {*[]} arr
* #param {number} [i] If not provided, check entire arr for empty.
* #return {boolean}
*/
const hasEmpty = (arr, i) => 0<=i
? !arr.some((_, j) => j==i)
: Object.values(arr).length!==arr.length;
Making it simple you can use the below comparison for achieving the same.
function hasEmptyElement(array){
for(var i=0;i<array.length;i++){
if(my_arr[i] === "")
return false;
}
return true;
}
hello try this....
if (typeof arr[i] == 'NULL'){
return true;
}
hope this may work
I am new to JS and am trying to understand chartAt. I created a problem where I want to go through an array and pull the first character of each value from my array using charAt. I'm a bit stuck with my code.
var myArray = ['adam', 'bianca', 'cat', 'dennis'];
var myFunc = function (letter) {
for (var i = 0; i < letter.length; i += 1) {
letter.charAt(0);
console.log(letter.charAt(0));
}
}
In your iteration loop, letter is the array passed to the function myFunc(). You need to access its elements, which you're iterating via i. Use letter[i].charAt(0) instead of letter.charAt(0)
var myArray = ['adam', 'bianca', 'cat', 'dennis'];
var myFunc = function (letter) {
for (var i = 0; i < letter.length; i += 1) {
// Use the index i here
console.log(letter[i].charAt(0));
}
}
// Call your function, passing in the array you defined:
myFunc(myArray);
// a
// b
// c
// d
So your understanding of String.prototype.charAt() is correct, but the loop iteration was faulty.
If what you want to do is go through each element in the array and get the first letter, you need to iterate over the array, not the word (which you call letter in your solution. So you would have something like this:
for( var i=0; i<myArray.length; i++ ) {
console.log( myArray[i].charAt(0) );
}
Or:
myArray.forEach( function(word){
console.log( word.charAt(0) );
});
Also, you're creating a function (myFunc), but then you're never actually invoking it.
Seems about right, except that you coded a constant in your loop instead of using the loop variable:
var myArray = ['adam', 'bianca', 'cat', 'dennis'];
var myFunc = function (letter) {
for (var i = 0; i < letter.length; i += 1) {
letter.charAt(i);
console.log(letter.charAt(i));
}
}
> myFunc(myArray[1])
b VM622:6
i VM622:6
a VM622:6
n VM622:6
c VM622:6
a VM622:6
undefined
You might also want to print out the whole array:
for (var word in myArray) {
word = myArray[word];
console.log("");
myFunc(word);
}
if you using jQuery
var myArray = ['adam', 'bianca', 'cat', 'dennis'];
$.each(myArray,function(){console.log(this.charAt(0))});
If you are using ES6
const myArray = ['adam', 'bianca', 'cat', 'dennis'];
myArray.forEach(myFunc => console.log(myFunc.charAt(0)));
//output
a
b
c
d
If you want to put the output in an array
const myArray = ['adam', 'bianca', 'cat', 'dennis'];
const myFunc = myArray.map(name => name.charAt(0));
console.log(myFunc);
//output
[ 'a', 'b', 'c', 'd' ]
// When .map() is called on an array, it takes an argument of a callback function and returns a new array
I am trying to check if an element exists in any one of three arrays. I don't know how to return the name of the array where the element was found. Can anyone direct me into the right direction please.
I have coded a function which takes the element in search as its argument and then returns the array name:
var arr1 = ['a','b','c','d'];
var arr2 = ['e','f','g','h'];
var arr3 = ['i','j','k','l'];
function chkElem(elem)
{
var id = elem;
var isFound = null;
if(arr1.indexOf(id) || (arr2.indexOf(id) || (arr3.indexOf(id))))
{
isFound = ????
}
return isFound;
}
I am uncertain how to assign the parent array name to 'isFound' variable.
Thanks.
You should never use "variable names" in your function logic. Instead, make the arrays properties of an object and return the property name:
var arrays = {
"arr1": ['a','b','c','d'],
"arr2": ['e','f','g','h'],
"arr3": ['i','j','k','l']
};
for (var name in arrays)
if (arrays[name].indexOf(id) > -1)
return name;
return null;
Or, even better, use an array of arrays to search in and return the index:
var arrays = [
['a','b','c','d'],
['e','f','g','h'],
['i','j','k','l']
];
for (var i=0; i<arrays.length; i++)
if (arrays[i].indexOf(id) > -1)
return i;
return -1;
Test one-by-one:
if (arr1.indexOf(id) > -1) {
isFound = arr1;
} else if (arr2.indexOf(id) > -1) {
isFound = arr2;
} else if (arr3.indexOf(id) > -1) {
isFound = arr3;
}
Alternatively, create a multi-dimensional array:
var arr = [
['a','b','c','d'],
['e','f','g','h'],
['i','j','k','l']
];
var isFound = null;
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf(elem) > -1) {
isFound = arr[i];
break;
}
}
Firstly, be careful of the indexOf() trap - if it fails to find the requested string, it will return -1 - which is a truthy - so you need to check explicitly like so:
if (arr1.indexOf(id) != -1)
not
if (arr1.indexOf(id))
The truthy/falsy concept also means that, if your string is the first element in the array, and so indexOf() returns false, that is a falsy, and so your condition will actually fail even though a match was made!
Secondly, you cannot return the name of the array - or, to be more precise, the name of the variable that references it in the JS memory. You can either:
1) return the array itself
if (arr1.indexOf(id) != -1) return arr1;
2) store your arrays in a central object and return the name of the property that you found it in
var arrs = {
'one': ['foo', 'bar']
/* two, three etc */
};
for(var i in arrs)
if (arrs[i].indexOf('foo') != -1)
return i;
When you have a group of things, store them in an array (if they are ordered) or an object (if they are named). If you spot a bunch of variables with almost identical names, you're probably doing something wrong.
var things = [
['a','b','c','d'],
['e','f','g','h'],
['i','j','k','l']
];
Then you can loop over them:
for (var i = 0; i < things.length; i++) {
var thing = things[i];
if (thing.indexOf(id) > -1) { // indexOf returns -1 if not found, and the index (starting from 0) if it is.
return i;
}
}
return null;
var arr1 = ['a', 'b', 'c', 'd'];
var arr2 = ['e', 'f', 'g', 'h'];
var arr3 = ['i', 'j', 'k', 'l'];
function chkElem(elem) {
var isFound;
(isFound = arr1).indexOf(elem) > -1 || (isFound = arr2).indexOf(elem) > -1 || (isFound = arr3).indexOf(elem) > -1;
return isFound;
}
alert(chkElem('f'));