I need a function that basically just multiplies members of an array by 100. The number of members of the array may change. Also, I can't use something like array.prototype.map - it has to be a loop.
Here's what I've got so far, but newArray comes back as undefined... What am I doing wrong?
var a = [1, 2, 3];
function toPts(array){
for(var i=0; i<array.length; i++){
array[i] *= 100;
}
}
var newArray = toPts(a);
The end result needed is newArray = [100, 200, 300]
You forgot to return the array. If you just want to modify existing one, you only need to do:
toPts(a);
console.log(a) // [100,200,300]
If you want a new array with original untouched:
function toPts(array){
var arr = array.slice(0); // copy array to new reference
for(var i=0; i<arr.length; i++){
arr[i] *= 100;
}
return arr;
}
var newArray = toPts(a);
console.log(newArray) // [100,200,300]
console.log(a) // [1,2,3]
function toPts(array){
for(var i=0; i<array.length; i++){
array[i] *= 100;
}
return array;
}
You didn't return the array to the outside.
However, note you are modifying the original array, so it doesn't make much sense to have it in two variables.
Probably, you want to copy it:
function toPts(array){
var newArray = array.slice();
for(var i=0; i<newArray.length; i++){
newArray[i] *= 100;
}
return newArray;
}
var a = [1, 2, 3],
newArray = toPts(a); // `a` is not altered
a is multiplied in-place as its passed by reference, so after the function (which returns nothing)
toPts(a);
alert(a) // 100,200,300
you are not returning anything from the function,
you just need to return the modified array inside the function (after the loop has finished executing)
like
var a = [1, 2, 3];
function toPts(array){
for(var i=0; i<array.length; i++){
array[i] *= 100;
}
return array;
}
var newArray = toPts(a);
by default function return undefined when it does not return anything.your a array already changed to resulted array.
var a = [1, 2, 3];
function toPts(array){
for(var i=0; i<array.length; i++){
array[i] *= 100;
}
}
console.log(a);//this give you resulted output becuse array is passing as call by reference. so changes made in the same array
Related
I have an array that contains elements my goal is to slice some of the elements inside the array, then later I want to reassign the original array with a new array which is a sublist of the original array but it seems like I can't make that happen please help.
let arr = [1,2,3,4,5]
function subList(arr){
for(let i = 0; i < arr.length; i++){
let res = arr.slice(0,i)
if(i === 3){
arr = res;
}
}
}
subList(arr)
console.log(arr)
// expected output [1,2,3]
There are a lot of ways to do it.
Why it isn't working for you:
You are passing the arr into the variable and since it is an object ideally any change you make to it should be reflected outside. But you aren't actually mutating/changing anything in your passed argument, you are reassigning it (with arr=res). So that will not make any change to the arr outside.
If you do something like .push(),.pop(), which are operations on the array without reassigning it, that should actually change it.
Example modifying your code with operations that actually modify the array instead of replacing it splice() , push:
let arr = [1,2,3,4,5]
function subList(arr){
for(let i = 0; i < arr.length; i++){
let res = arr.slice(0,i)
if(i === 3){
arr.splice(0,arr.length);
arr.push(...res);
break;
}
}
}
subList(arr)
console.log(arr)
Pass in an index to the function and just return arr.slice(0, i);.
let arr = [1, 2, 3, 4, 5]
function subList(arr, i) {
return arr.slice(0, i);
}
console.log(subList(arr, 3));
let list = [1,2,3,4,5]
function subList(arr,n){
for(let i = 0; i < arr.length; i++){
if(i === 3){
let res = arr.slice(0,i)
list = res;
}
}
}
subList(list,0)
console.log(list)
I'm trying to get indices of array elements. I'm going to use it for Leetcode question "Create Target Array in the Given Order".
Right now I wrote the following code but it doesn't work. (returns undefined)
var createTargetArray = function(nums) {
for(var i=0; i<nums.length; i++) {
console.log(nums.indexOf[i])
}
};
const num = [1,2,3,4,0,108];
createTargetArray(num);
Expected output from that code: [0, 1, 2, 3, 4, 5]
Am I using indexOf method incorrectly?
To get the index of the numbers, you have to call indexOf as a function call (indexOf(i))and not an array accessor (indexOf[i])
Try running the snippet below to check.
var createTargetArray = function(nums) {
for(var i=0; i<nums.length; i++) {
console.log(nums.indexOf(i))
}
};
const num = [1,2,3,4,0,108];
createTargetArray(num);
And if you want the index of exery number, that's just your variable i. You don't need to call the indexOf method.
var createTargetArray = function(nums) {
for(var i=0; i<nums.length; i++) {
console.log(i)
}
};
const num = [1,2,3,4,0,108];
createTargetArray(num);
var createTargetArray = function(nums) {
for(var i=0; i<nums.length; i++) {
console.log(nums.indexOf[i]) // <--mistake
}
};
indexOf is a method
console.log(nums.indexOf(nums[i]));
But since you are looping through the array sequentially output will always be [0, 1, 2, ... n]
I've been trying and searching how to loop through the params to check if those already exist in an array, i haven't got it fully working but when there is a duplicate value it dose not return at all.
The idear is pass multiple values is param then loop through those vals and only push if it dose not exist in the array.
var arr = [7,3,1];
function pushNew(obj) {
var prams = obj;
for(var k = 0; k < obj.length; k++){
for (var i = 0; i < arr.length; i++) {
if (arr[i] == prams[k]) {
return;
}
}
array.push(prams[k]);
}
// console.info(arr);
}
pushNew([2,7,4]);
A short and more modern way to just get all the unique values is to use Array.from with Set. A Set is an array-like structure that will only hold unique values. Array.from converts an array-like structure into a real array.
In your case, you can just concat both arrays, pass them to Set to remove the duplicates, and use Array.from to convert it back to a regular array.
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [3, 4, 5, 6, 7];
var result = Array.from(new Set(arr1.concat(arr2)));
document.write(JSON.stringify(result));
Actually, your existing code nearly works.
You can set a flag if you find a match in the inner loop and instead of return you should use break to escape the loop. Then use push after the inner loop if a match wasn't found. Also, there is no need for both obj and prams (which I've renamed to params), so:
var arr = [7,3,1];
function pushNew(params) {
var found;
for(var k=0; k<params.length; k++){
// Set found to initial value on each outer loop
found = false;
for (var i=0; i<arr.length; i++) {
// If find match, set flag and break from loop (for efficiency)
if (arr[i] == params[k]) {
found = true;
break;
}
}
// If match not found, push into arr
if (!found) arr.push(params[k]);
}
}
pushNew([7,2])
document.write(arr); // 7,3,1,2
If you want efficient code, consider creating an index and using in:
var arr = [7,3,1];
function addParams(params) {
var index = arr.reduce(function(acc, v) {
acc[v] = true;
return acc;
},{});
params.forEach(function(v) {
if (!(v in index)) arr.push(v);
});
}
addParams([7,3,2]);
document.write(arr);
You can use indexOf to validate if element is present in an array. forEach is another array method which works like loop.
var arr = [7,3,1];
function pushNew(obj) {
//var prams = obj;
obj.forEach(function(item){ // iterate through each element
if(arr.indexOf(item) == -1){ //indexOf return -1 is element is not present in an array
arr.push(item)
}
})
console.log(arr);
}
pushNew([2,7,4]);
Working Jsfiddle
var arr = [7, 3, 1];
function pushNew(obj) {
for (var k = 0; k < obj.length; k++) {
if (arr.indexOf(obj[k]) == -1) {
arr.push(obj[k]);
}
}
}
pushNew([2, 7, 4]);
You can use _.union function of lodash.
_.union([2, 1], [4, 2], [1, 2]);
// → [2, 1, 4]
I have an array and an array of objects. I want to search each value in the array in the array of objects and if it doesnt exist, I want to remove the value from the array.
var arr= [1,2,3,4];
var recs = [{id:1},{id:2},{id:3}]; //4 doesnt exist in recs, remove from arr
//arr = [1,2,3];
Heres my attempt. Obviously does not work. I am not sure how I can compare each arr index with all the values in recs before moving on the next arr index:
var arr= [1, 2, 3, 4], index;
var recs = [{a:1},{a:2},{a:3}];
for(var i = 0; i<arr.length; i++){
for(var val in recs[i]){
if(arr[i] != recs[i][val]){
index = arr.indexOf(arr[i]);
arr.splice(index, 1);
}
}
}
thank you!!
If you are okay with leaving your original array instance alone and creating a new one (essentially treating it as immutable)
var newArr = arr.filter(function(num) {
return !recs.every(function(obj) {
return obj.a !== num;
});
});
Detail of the methods used: Array.filter is passed a function, runs that function on each element inside, and then returns a new array with only the elements that returned true in the function.
Array.every works a little similar, but returns a Boolean, true or false. It returns true if all of the elements of the array returned true inside of the function.
var arr= [1, 2, 3, 4];
var recs = [{a:1},{a:2},{a:3}];
// don't use var in for loops.
// Variables declared with var have function scope, so declare them at the top of your function
var i;
var j;
var value;
var found;
// iterate over the array
for (i = 0; i < arr.length; i++)
{
value = arr[i];
found = false;
// iterate over the other array
for (j = 0 ; j < recs.length ; j++)
{
// if we found what we were looking for, make a note and exit loop
if (recs[j].a == value)
{
found = true;
break;
}
}
if (!found)
{
arr.splice(i, 1);
// To compensate the loop's i++, to avoid skipping the next entry
i--;
}
}
alert(arr.join(','));
How can I remove an object from a copy of an array without removing it from the original?
I have a global variable :
var userTrickList = [];
And inside a function, I make a copy of that global array :
var tempUserTrickList = userTrickList;
Then I use the removeItem function that I created to remove a certain object.
removeItem(considerTrick.IDName, tempUserTrickList);
function removeItem(item, list) {
//takes a string as 'item', finds in the array as 'list',
//then removes it from the list.
for(var i = 0; i < list.length; i++)
{
if(item === list[i])
{
list.splice(i,1);
}
}
}
My problem is, this function removes it from the userTrickList too.
Any ideas? It's definitely a problem in "removeItem(considerTrick.IDName, tempUserTrickList);", but I can't think of a solution.
Use .slice(0) to clone an array.
var tempUserTrickList = userTrickList.slice(0);
Credits:
http://davidwalsh.name/javascript-clone-array
use this function for your requirement
function removeElementFromArray(data,target) {
var temp=new Array();
for ( var i = 0; i < data.length; i++) {
if(data[i]!=target){
temp.push(data[i]);
}
}
return temp; }
here data is original array and target is the element you want to remove from array
this function will return array without containing the removed item.
Try, It copy the original array
var tempUserTrickList = JSON.parse(JSON.stringify(userTrickList));
Demo CopyArray
for (i = 0, l = arr.length; i < l; i++) {
if (arr[i] === item) {
arr.splice(i, 1);
i -= 1;
l -= 1;
}
}
Daniel's method of cloning an array is absolutely correct, but since I don't see an ES6-oriented answer, I'll offer up an alternative solution:
We can just as easily use the spread operator to clone an array, so we don't have to use the slice call.
const arr = [1, 2, 3];
const copy = [...arr];
copy.pop();
console.log(arr); // returns [1, 2, 3]
console.log(copy); // returns [1, 2]