How to duplicate elements of an array in JavaScript and add them to the same array.
function duplicate(arr) {
// Write Logic here
var position,lengtharr = arr.length;
for(var i=0;i<lengtharr;++i){
arr[position] = arr[i];
position++;
}
return arr;
}
var arr=[1,2];
console.log(duplicate(arr));
Please explain why the above code is not working. I'm getting "Incorrect Output" as error.
Also, I've come up with another way as shown below. But I'd like to know what's wrong with this approach.
function duplicate(arr) {
// Write Logic here
var lengtharr = arr.length;
for(var i=0;i<lengtharr;++i){
arr.push(arr[i]);
}
return arr;
}
var arr=[1,2];
console.log(duplicate(arr));
Thank you
An alternative approach would be to use push to add elements to the end of the array. That way you don't need that extra position variable.
function duplicate(arr) {
const len = arr.length;
for (let i = 0; i < len; ++i) {
arr.push(arr[i]);
}
return arr;
}
let arr= [1, 2];
console.log(duplicate(arr));
You can achieve this by using Spread syntax (...)
Try this :
function clone(arr) {
arr.push(...arr);
return arr;
}
var arr=[1,2];
console.log(clone(arr));
Related
I need to create function that creates and returns array. Its size needs to match the rows parameter, and each next element contains consecutive integers starting at 1. To call this function I need to use argument 5. Here below is what I wrote so far. Can you tell me what's wrong here?
function createArray(rows) {
for(let i = 1; i < rows.length; i++) {
console.log(rows[i]);
}return rows;
}
createArray(5);
You need to create an array and return it, whereas you return just rows which is a number. The idea of using a for loop is the best way to go. In that loop you just need to set the values in the array accordinlgy.
Another problem in your code is that rows is of type number and does have a property length but that does not have the desired value. So we just use rows in the for loop. We start the loop with i = 0 because array indices start at 0.
Code
function createArray(rows) {
let arr = new Array(rows);
for (let i = 0; i < rows; i++) {
arr[i] = i + 1;
}
return arr;
}
console.log(createArray(5));
We can not use length property for number. create an empty array and then push values into that array until required size is achieved.
function createArray(rows) {
var arr = [];
for(let i = 1; i <= rows; i++) {
arr.push(i);
}return arr;
}
createArray(5);
I think what you want is createArray(5) return [1,2,3,4,5] if that's the case you could do this
function createArray(rows) {
const arr = []
for(let i = 1; i <= rows; i++) {
arr.push(i);
}
return arr;
}
console.log(createArray(5));
The problem is, that rows.length is not available on 5, because 5 is a number.
You have to use an array as parameter:
Array(5) creates an array with the length of 5 and fill("hello") fills this array with "hello" values.
function createArray(rows) {
for (let i = 1; i < rows.length; i++) {
console.log(rows[i]);
}
return rows;
}
const rows = Array(5).fill("hello");
createArray(rows);
I don't know, if this is the behaviour you want, if not, I misunderstood your question.
for (var i = 0; i < firstString.length; i++) {
newArray.push(i);
return newArray;
}
What code am i missing? Outputting [0], when i want to output [0,1,2,3,4,5,6]
What exactly am i doing with my code, since it's not what i think?
I've seen this --->
function someFunction(n){
var newArray = [];
for(var i=0; i < n.length; i++){
newArray.push(n[i]);
}
return newArray;
}
but i'm not looking to get the length of a function.
return will cause the code to exit the current method. Since you have put the return inside the for loop, your method is exiting after the first pass through the loop, thus returning only the output [0].
Move your return newArray; outside the loop.
Move the return statement out of the for loop, because it exits the function and the iteration.
for (var i = 0; i < firstString.length; i++) {
newArray.push(i);
}
return newArray;
Why isn't this working?
ps. I don't want to use any other variable to make it work, and i don't want to use built in functions, just asking why THIS is not working?
function reverse(arr){
for(var i =0; i< arr.length; i++){
arr.push(arr[arr.length-i]);
}
return arr;
}
There are a lot of flaws in your code.
When you start pushing arr.push(arr[arr.length-i]); the array length increases, thereby, you won't get a consistency in the data.
This goes inside an infinite loop, as every time, the arr is ahead of its length.
It is better to use another variable and reverse, or you can use the built-in reverse() function. There's nothing wrong in having another variable and add temporary contents in it.
Solutions:
Using a temporary array:
function reverse(arr) {
var final = [];
for (var i = arr.length - 1; i >= 0; i--) {
final.push(arr[i]);
}
return final;
}
Using built-in function (Array.prototype.reverse()):
function reverse(arr) {
return arr.reverse();
}
Using few temporary variables:
a = [5,4,3,2,1];
function reverse(arr) {
var i = 0, j = arr.length - 1;
for (i = 0; i < j; i++, j--) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
console.log(reverse(a));
You're going to run out of memory. What you're doing is adding what was initially the last element of that array infinitely to the end of your array. Every time that you call arr.push(...) you increase arr.length by one. Your for loop will never be able to finish because i will never be less than arr.length
I don't want to use any other variable to make it work, and i don't want to use built in functions
You cannot.
Use temporary array for result
function reverse(arr) {
var res = []
for (var i = arr.length - 1; i > -1; i--) {
res.push(arr[i]);
}
return res;
}
I don't really know how to ask this and maybe that is why I can't properly find the answer to this problem.
So I have a very long list of numbers and I intend to put them in an array.
154,153,152,148,145,133,132,131,130,...,6,5,4,1 (You get the idea.)
The problem is that I'm lazy and don't want to type out all the numbers out into this "initial" array. (Notice that there are sequential strings of numbers in the list.)
I thought I could do something like this:
var array = [154:152,148,133:130,...,6:4,1];
Which would yield something like this for array:
[154,153,152,148,133,132,131,130,...,6,5,4,1]
I know I can do a loop to fill these in. But the tricky parts are the "breaks" in the sequence.
Any help or obvious solution that I missed would be appreciated.
(This is for some code in google spreadsheets, which uses javascript as a basis.)
No, you can't do that natively.
You could however write a simple helper function which does it for you.
function createRange(arr) {
var result = [], //The resulting array
range;
for (var i = 0; i < arr.length; i++) {//Iterate over the array
if (Array.isArray(arr[i])) { //If we find another array
range = arr [i];
for (var j=range [0]; j <= range [1]; j++) {//increase its first element until it's equal the second
result.push(j); //add the number to the resulting array
}
} else { //If it's a number
result.push(arr[i]); //put it in the resulting array
}
}
return result; //return the array containing the range
}
createRange ([[1,5],10,[15,20]]) //[1, 2, 3, 4, 5, 10, 15, 16, 17, 18, 19, 20]
Heres a Fiddle as well
what do you think about this?
var a = ['154:152','148','133:130','6:4','1'];
var array = [];
for (i = 0; i < a.length; i++)
{
var b = a[i];
b = b.split(':');
if (b.length == 2)
{
for (var j = b[0]; j > b[1]-1; j--)
{
array[array.length] = j;
document.write(j);
}
}
else
{
array[array.length] = b[0];
document.write(b[0]);
}
}
I am trying to perform a simple indexOf on my array
the thing is that it just looks for the entire text within my array node
var arr = new Array();
arr.push("hello world");
var result = arr.indexOf("hello");
my problem is that the result I get is -1
is there any way to get the indexOf to search within each of the array element without another loop?
thanks
No, its not possible to use arr.indexOf to search for substring, you have to use loop.
Although you can add method to array to call it to find the substring in array.
Live Demo
Function definition.
arr.containsIndexOf = function(str) {
for(var i = 0; i < arr.length; i++){
if(arr[i].indexOf(str) != -1)
return i;
}
return -1;
}
Function call
arr.containsIndexOf("hello")
Like Adil said you need to use a loop.
var myArr= new Array();
myArr.push("hello world");
function searchArr(txt, arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].toLowerCase().indexOf(txt.toLowerCase()) > -1) {
return i
}
}
}
use this function like this
searchArr("hello",myArr); //returns 0
You might have a array with multiple "hello", so you need to know where all of them are.
myArr.push("hello world")
myArr.push("hello Pluto");
myArr.push("hi sun");
myArr.push("Hello Moon");
function searchArr(txt, arr) {
var arrList = new Array();
for (var i = 0; i < arr.length; i++) {
if (arr[i].toLowerCase().indexOf(txt.toLowerCase()) > -1) {
arrList.push(i);
}
}
return arrList
}
searchArr("hello",myArr); //returns [0, 1, 3]
As #Adil said, No you can't use indexOf function of Array to find substring but you can use indexOf of String to find substring:
Example:
var mystr = 'hello world';
var index = mystr.indexOf('hello');
With your example you should try somethings like:
var arr = new Array();
arr.push("hello world");
var mystr = arr[0]; // this is String object
var index = mystr.indexOf("hello");
Documentation:
string.indexOf
array.indexOf
Try this:
var arr = new Array();
arr.push("hello world");
var result = arr[0].indexOf("hello");
Because this is an Array so you need to access it with it's index.
You're pushing the whole of the string hello world into one index of the array so indexOf will only work when you use as it needs to match the whole item in that array index.
var result = arr.indexOf("hello world");
One way to do it would be like this:
var arr = new Array();
arr.push("hello world");
for(var i = 0; i < arr.length; i++){
if(arr[i].indexOf('hello') != -1)
return i;
}
See this jsfiddle
// Get index of the first matching item in an array
// or -1 if the item is not found
function SearchArray(arr, txt) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf(txt) > -1) {
return i;
}
}
return -1;
}
Function call:
var someArray = new Array();
someArray.push("hello world");
SearchArray(someArray, "hello");