i need make function like this:
Function add(arr,...newVal){
}
array = [1,2,3];
add(array,0)
console.log(array); //i need here to print [0,1,2,3]
iam make function as push like that:
Function add(arr,...newVal){
for(var i=0; i<arr.length; i++){
arr[arr.length]=newVal[i];
}return arr.length;
}
array = [1,2,3];
add(array,4)
console.log(array); // here to print [1,2,3,4]
const unshift = (arr, ...newVal) => {
let i= arr.length + newVal.length -1;
for( i ; i >= newVal.length; i--) {
arr[i] = arr[i - newVal.length ];
}
for(i; i >= 0; i--) {
arr[i] = newVal[i];
}
return arr;
}
Try this:
const unshift = (arr, newVal) => {
for(let i = arr.length; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = newVal;
return arr;
}
Related
Here is the code I have. I am pretty new to javascript still so I don't see why adding the function stops the for statement from incrementing the integers.
const arr = [10,10,16,12]
function incrementByOne(arr) {
// arr is an array of integers(numbers), Increment all items in the array by
// return the array
for (const i = 0; i < arr.length; i++){
arr[i] += 1;
}
return arr
}
Any help would be greatly appreciated.
I ran your code under Node.js:
Code:
'use strict';
const arr = [10,10,16,12]
function incrementByOne(arr) {
for (const i = 0; i < arr.length; i++) {
arr[i] += 1;
}
return arr
}
console.log(incrementByOne(arr));
Output:
$ node incr.js
incr.js:6
for (const i = 0; i < arr.length; i++){
TypeError: Assignment to constant variable.
at incrementByOne (incr.js:6:37)
$
As you can see, it complains that you are trying to change the value of i which your code said was constant. Write let i = 0 for a non-constant value.
Code:
'use strict';
const arr = [10,10,16,12]
function incrementByOne(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] += 1;
}
return arr
}
console.log(incrementByOne(arr));
Output:
$ node incr.js
[ 11, 11, 17, 13 ]
$
You could use map also:
const incrementByOne = (arr) => arr.map((element) => element + 1);
You should use let i = 0 instead of const i= 0 to initilize the loop iteration counter i
const arr = [10,10,16,12]
function incrementByOne(arr) {
// arr is an array of integers(numbers), Increment all items in the array by
// return the array
for (let i = 0; i < arr.length; i++){
arr[i] += 1;
}
return arr
}
Then call incrementByOne function
incrementByOne(arr);
const arr = [10,10,16,12]
function incrementByOne(arr) {
// arr is an array of integers(numbers), Increment all items in the array by
// return the array
for (let i = 0; i < arr.length; i++){
arr[i] += 1;
}
return arr
}
let a = incrementByOne(arr)
console.log(a)
I know it's a stupid question, but I only learning programming 3 months now.
How would you solve this problem, if you can't use higher order functions and built-in methods, like filter or indexOf?
Create a function that takes a list of numbers and returns a new list where all the duplicate values are removed
I got this so far, but I think It's a dead end...
const array = [1, 2, 3, 3, 1];
const removeDuplicate = () => {
let shortArray = [];
let index = 0;
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
if (i != j) {
if (array[i] == array[j]) {
shortArray[index] += array[i]
console.log(array[i]);
}
}
}
}
return shortArray;
}
console.log(removeDuplicate());
return this:
1
3
3
1
[ NaN ]
thanks!
Use an object as a helper. If a value appears in the helper, it's not unique and can be ignored. If it's not in the helper it's unique, push it into the result array, and add it to the helper object.
const array = [1, 2, 3, 3, 1];
const removeDuplicate = (arr) => {
const helperMap = {};
const result = [];
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (!helperMap[item]) {
result[result.length] = item;
helperMap[item] = true;
}
}
return result;
};
console.log(removeDuplicate(array));
function unique(arr) {
var obj = {};
for (var i = 0; i < arr.length; i++) {
var value = arr[i];
obj[value] = true; // set as key
}
return Object.keys(obj); //return all keys
}
Use below function:
function RemoveDuplicate(array){
let shortArray = [];
let index = 0;
for (let i = 0; i < array.length; i++) {
let exist=false;
for(let j=0;j<shortArray.length;j++){
if(array[i]==shortArray[j]){
exist=true;
break;
}
}
if(!exist){
shortArray[shortArray.length]=array[i];
}
}
return shortArray;
}
I need to find the length of the longest string in the given array. It should return 0 if the array is empty.
So here's my try:
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for(var i=0; i< arr.length; i++){
if(arr[i] > biggestNum){
biggestNum = arr[i];
}
}
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output); // --> MUST RETURN 5
But this one did not work. Any idea or is there any better option to do this?
To throw another alternative into the mix: Math.max can be fed the lengths as arguments (by mapping them on the input) to get the longest string:
function getLengthOfLongestElement(arr) {
return Math.max(0,...arr.map(s=>s.length));
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output);
This is apparently a reducing job and can simply be implemented as follows;
var ss = ['one', 'two', 'three'],
ln = ss.reduce((r,s) => r > s.length ? r : s.length, 0);
console.log(ln);
You should test with arr[i].length instead of arr[i] and you should return biggestNum at the end of your function:
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > biggestNum) {
biggestNum = arr[i].length;
}
}
return biggestNum;
}
Demo:
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > biggestNum) {
biggestNum = arr[i].length;
}
}
return biggestNum;
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output);
You should use the string length property. So instead of arr[i] it will be arr[i].length
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > biggestNum) {
biggestNum = arr[i].length;
}
}
return biggestNum;
}
My preferred solution is using reduce.
const arr = ['one', 'two', 'three'];
const maxLength = arr.reduce((acc, item) => Math.max(acc, item.length), 0);
console.log(maxLength)
For zero element just check if the array length is zero or not else arr[i].length will return the length of the string
function getLengthOfLongestElement(arr) {
var biggestNum = 0;
if (arr.length > 0) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].length > biggestNum) {
biggestNum = arr[i].length;
}
}
} else if (arr.length == 0) {
biggestNum = 0
}
return biggestNum
}
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output);
I'm having trouble with a function returning the original array as opposed to the sorted array. I tried to slice the array and return the sorted but it is not working. Any ideas on how to fix this?
function sortArr( comparator, array ){
var newArray = array.slice();
for(var i = 0; i < newArray.size; i++)
{
var min = i;
for(var x = i; x < newArray.size; x++)
{
if(comparator(newArray[min],newArray[x]) == true)
{
min = x;
}
}
var temp = newArray[i];
newArray[i] = newArray[min];
newArray[min] = temp;
}
return newArray;
}
I fixed the function:
function sortArr( comparator, array ){
/*your code here*/
var i, x;
var min;
var newArray = array.slice();
for(i = 0; i < newArray.length - 1; i++)
{
min = i;
for(x = i + 1; x < newArray.length; x++)
{
if(comparator(newArray[min],newArray[x]) == true)
{
min = x;
}
}
if(min != i){
var temp = newArray[i];
newArray[i] = newArray[min];
newArray[min] = temp;
}
}
return newArray;
}
Copy the array with slice and then use native sort:
function sortArr(comparator, array) {
return array.slice().sort(function(a,b) {
return comparator(a,b) * 2 - 1;
});
}
Your sorting algorithm doesn't look quite right. For a start the swapping of values should be inside the if statement. I would also advise to look at #Oriol's solution which is far more elegant.
function sortArr( comparator, array ){
var newArray = array.slice();
for(var i = 0; i < newArray.size; i++)
{
var min = i;
for(var x = i; x < newArray.size; x++)
{
if(comparator(newArray[min],newArray[x]) == true)
{
var temp = newArray[i];
newArray[i] = newArray[min];
newArray[min] = temp;
min = x;
}
}
}
return newArray;
}
{"index.js":"var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
let newArr = globalArray.slice();\n let emptyArr = [];
return emptyArr.concat(newArr).sort();
}
nonMutatingSort(globalArray);"}
how to find duplicates in an array and remove them using javascript?
To do this generically, you could use something like the following, which removes duplicates from the array in place. If you have an array that contains only strings or numbers, you could simplify this significantly.
var arrayContains = Array.prototype.indexOf ?
function(arr, val) {
return arr.indexOf(val) > -1;
} :
function(arr, val) {
var i = arr.length;
while (i--) {
if (arr[i] === val) {
return true;
}
}
return false;
}
function removeDuplicates(arr, equals) {
var val, originalArr = arr.slice(0);
arr.length = 0;
for (var i = 0, len = originalArr.length; i < len; ++i) {
val = originalArr[i];
if (!arrayContains(arr, val)) {
arr.push(val);
}
}
return arr;
}
var arr = [1, 2, 2, 1, 3];
removeDuplicates(arr);
console.log(arr); // [1, 2, 3]
var sampleArr=new Array(1,1,1,1,1,2,2,3,3,3,4,4,4); //Declare array
document.write(uniqueArr(sampleArr)); //Print the unique value
//Adds new uniqueArr values to temp array
function uniqueArr(a) {
temp = new Array();
for(i=0;i<a.length;i++){
if(!contains(temp, a[i])){
temp.length+=1;
temp[temp.length-1]=a[i];
}
}
return temp;
}
//Will check for the Uniqueness
function contains(a, e) {
for(j=0;j<a.length;j++)if(a[j]==e)return true;
return false;
}
for(var i=0; i < arr.length; i++)
{
for(var j=i+1; j < arr.length; j++)
{
if(arr[j] == arr[i])
{
arr.splice(j, 1);
}
}
}