Array Elements In JavaScript Printing Into Seperate Arrays - javascript

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

Related

How to split a string and repeat characters? [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 3 years ago.
I'm trying to convert the array = ["A", "B", "C", "D"] into array = ["A", "BB", "CCC", "DDDD"]. If you compared the arrays, you'll notice that the letters inside the second array have extra same letters in each position. Here is my code below. I used the for loop because I wanted to use the increment inside the for loop. I don't even know if map() method can do the same so I went with for loop. However, when I checked, it didn't show the result that I wanted. What did I miss?
function accum(s) {
// your code
let accArray = s.toUpperCase().split("");
for (let i = 1; i < accArray.length; i++) {
accArray[i].repeat(i + 1);
}
console.log(accArray);
}
accum("abcd")
A more concise way to achieve the desired output is to use Arrow Functions:
const accum = (s) => s.toUpperCase()
.split("")
.map((s, i) => s.repeat(i + 1));
console.log(accum("abcd"));
String.prototype.repeat()
The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
You have to assign the new returned value at the specific index:
accArray[i] = accArray[i].repeat(i + 1);
function accum(s) {
// your code
let accArray = s.toUpperCase().split("");
for (let i = 1; i < accArray.length; i++) {
accArray[i] = accArray[i].repeat(i + 1);
}
console.log(accArray);
}
accum("abcd")
You need to push values to array, or assign back to that index, repeat does not mutate the original value it returns a new string Repeat so you need to assign it back
function accum(s) {
// your code
let accArray = s.toUpperCase().split("");
let op = []
for (let i = 0; i < accArray.length; i++) {
op.push(accArray[i].repeat(i + 1));
}
console.log(op);
}
accum("abcd")
if your input is already an array like
arr = ['a', 'b', 'c', 'd']
then you can use
arr.map((item, idx) => item.repeat(idx+1))
if you are having string like
str = 'abcd'
then you can use:
str.split('').map((item, idx) => item.repeat(idx+1);
You can use forEach or map both work perfectly as iterator
function accum(s) {
// your code
let accArray = s.toUpperCase().split("");
const arr = [];
accArray.forEach((e, index) => {
arr.push(e.repeat(index + 1))
})
console.log(arr);
}
accum("abcd")

Modify an array of dictionaries, to add an element in each

How could I add an additional key value pair to each element in the following array.
get_project_list.completed = [{"user":"xyz","email":"a#123.com"}]
for (var i in get_project_list.completed) {
i['status'] = "completed";
}
O/P [{"user":"xyz","email":"a#123.com","status":"completed"}]
There should be a simple solution to this but couldn't find one which worked.
Any help is appreciated.
Don't use for in loop for arrays, because it iterates over every enumerable property.
For example here I add to the array a new property, which is enumerable and in the for in loop I get it also.
var arr = [{"user":"xyz","email":"a#123.com"}];
Object.defineProperty(arr, 'custom', { value: 'myCustom', enumerable: true });
for(let prop in arr){
console.log(prop);
}
If you are using ES6 you can do via
1) forEach function
var arr = [{"user":"xyz","email":"a#123.com"}];
arr.forEach(item => item['status'] = 'completed');
console.log(arr);
2) for of loop
var arr = [{"user":"xyz","email":"a#123.com"}];
for(let item of arr){
item['status'] = 'completed';
}
console.log(arr);
With ES5, you can use simple for loop
var arr = [{"user":"xyz","email":"a#123.com"}];
for(var i = 0; i < arr.length; i++){
arr[i]['status'] = 'completed'; // get the current index-th item
}
console.log(arr);
You get the index in the for loop and need to use it together with the array.
get_project_list.completed[i]['status'] = "completed";
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
var get_project_list = { completed: [{"user":"xyz","email":"a#123.com"}] },
i;
for (i in get_project_list.completed) {
get_project_list.completed[i]['status'] = "completed";
}
console.log(get_project_list);
For arrays, I suggest to use a for loop with a counter, because you get all enumerable properties and the order is not guaranteed.
var get_project_list = { completed: [{"user":"xyz","email":"a#123.com"}] },
i;
for (i = 0; i <get_project_list.completed.length; i++) {
get_project_list.completed[i]['status'] = "completed";
}
console.log(get_project_list);
If you're transpiling (e.g. with Babel), I'd suggest using a map function in combination with the object spread operator instead.
let newList = get_project_list.completed.map(i =>
{... i, status : "completed" }
)
This way, you don't have to mutate the old array.

For loop array confusion

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"]

splitting array elements in javascript split function

Hi i have the below array element
var array =["a.READ","b.CREATE"]
I'm trying to split the elements based on "." using javascript split method
below is my code
var array1=new Array();
var array2 = new Array();
for (var i = 0; i < array .length; i++) {
array1.push(array [i].split("."));
}
console.log("this is the array1 finish ----"+array1)
The out put that i'm receiving is
[["a","READ"],["b","CREATE"]]
The expected output that i want is
array1 =["a","b"]
array2=["READ","CREATE"]
I'm stuck here any solution regarding this is much helpful
You need to add to array2 and use both elements from the returned array that String.prototype.split returns - i.e. 0 is the left hand side and 1 is the right hand side of the dot.
var array = ["a.READ", "b.CREATE"]
var array1 = []; // better to define using [] instead of new Array();
var array2 = [];
for (var i = 0; i < array.length; i++) {
var split = array[i].split("."); // just split once
array1.push(split[0]); // before the dot
array2.push(split[1]); // after the dot
}
console.log("array1", array1);
console.log("array2", array2);
We'll start off with a generic transpose function for two-dimensional arrays:
function transpose(arr1) { // to transpose a 2d array
return arr1[0].map( // take the first sub-array and map
function(_, i) { // each element into
return arr1.map( // an array which maps
function(col) { // each subarray into
return col[i]; // the corresponding elt value
}
);
}
);
}
Now the solution is just
transpose( // transpose the two-dimensional array
array.map( // created by taking the array and mapping
function(e) { // each element "a.READ" into
return e.split('.'); // an array created by splitting it on '.'
}
)
)
You are adding nothing to array2. Please use indexes properly , like below:
var array1=new Array();
var array2 = new Array();
for (var i = 0; i < array .length; i++) {
array1.push(array [i].split(".")[0]);
array2.push(array [i].split(".")[1]);
}
you can do something like this
var array =["a.READ","b.CREATE"];
var arr1= [], arr2= [];
array.forEach(function(item,index,arr){
item.split('.').forEach(function(item,index,arr){
if(index % 2 === 0){
arr1.push(item);
}else{
arr2.push(item);
}
});
});
console.log(arr1);
console.log(arr2);
DEMO
I guess this is a bit redundant but, the split method actually returns and array. Although your code was off you were not modifying array2. Consider the following.
var array = [ "a.READ" , "b.CREATE" ]
, array1 = []
, array2 = []
// cache array length
, len = array.length;
for ( var i = 0; i < len; i++ ) {
// the split method returns a new array
// so we will cache the array
// push element 0 to array1
// push element 1 to array2
var newArr = array[ i ].split('.');
array1.push( newArr[ 0 ] );
array2.push( newArr[ 1 ] );
}
console.log( 'array1: ', array1 );
console.log( 'array2: ', array2 );
Use this:
for (var i = 0; i < array .length; i++) {
var parts = array[i].split('.');
array1.push(parts[0]);
array2.push(parts[1]);
}
You have not assigned any value to Array2. You can do as shown below.
var array1=[];
var array2 = [];
for (var i = 0; i < array .length; i++) {
var arrayTemp=[];
arrayTemp.push(array [i].split("."));
array1.push(arrayTemp[0]);
array2.push(arrayTemp[1]);
}

loop over array using charAt to get first letter of each value in javascript

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

Categories

Resources