How to get index of array elements by looping through - javascript

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]

Related

push to object if not exists from params

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]

Reversing certain number of elements in an array javascript

I am working on a code where I need to reverse certain no of elements in an array and rest should remain same. For example is an array has values of 1,2,3,4,5,6 and I have to reverse 4 elements of it then output should be 4,3,2,1,5,6. I am using below code to achieve this but getting error, please suggest.
function reverseArray(n, a) {
var interimArray1 = [];
//var interimArray2=[];
//var finalArray=[];
for (var i < n; i >= 0; i--) {
interimArray1.push[a[i]];
}
for (var i = n; i < a.length; i++) {
interimArray1.push[a[i]];
}
for (var i = 0; i < interimArray1.length; i++) {
console.log(interimArray1[i]);
}
}
var arr = [1, 2, 3, 4, 5, 6];
var num = 4;
reverseArray(num, arr);
The error in your code is that you intend to call the push method on a[i] like so:
interimArray1.push(a[i]);
but instead you write:
interimArray1.push[a[i]];
You make that mistake twice. To give arguments to the push method, you must use round parenthesis ().
With that fixed, you will see that your code works perfectly.
You can use Array#slice, Array#splice as follow.
function partialReverse(arr, num, from = 0) {
var slicedArr = arr.slice(from, num + from);
arr.splice(from, num); // Remove `num` items from array
arr.splice(from, 0, ...slicedArr.reverse()); // Add `num` reversed items
return arr;
}
var arr = [1, 2, 3, 4, 5, 6];
console.log(partialReverse(arr, 4, 0)); // Reverse four items from `arr` starting from 0th index
console.log(partialReverse(arr, 4, 1)); // Reverse four items from `arr` starting from 1st index
Lots of hints but you seem to be missing them. ;-)
You need to assign an initial value to i, so:
for (var i = n; ... )
===========^
Also, you need to use () to call functions, not [], so:
interimArray1.push(a[i]);
==================^====^
Same in the following for block. Otherwise, the code works though it's more verbose than it needs to be.
This is working :
I'm sure there are faster ways of doing it. Also, it will only work for elements at the beginning of the array but you can adjust the function for what you want to achieve.
var reverseArray = function(arr,elementsToReverse) {
var tempArrayRev = [];
var tempArray = [];
for (var i=0;i<arr.length;i++) {
if (i < elementsToReverse) {
tempArrayRev[i] = arr[i];
} else {
tempArray.push(arr[i]);
}
}
return tempArrayRev.reverse().concat(tempArray);
}
var array = [1,2,3,4,5,6];
document.getElementById('arrayOutput').innerHTML += reverseArray(array,4);
<div id="arrayOutput">Array :<br></div>
This is the answer you can test it.
function reverseArray(n, a) {
var interimArray1 = [];
for (var i = 0; i < a.length; i++) {
interimArray1.push(a[i]);
}
for (var i = num; i >=0; i--) {
interimArray1[i-1] = a[n - i];
}
for (var i = 0; i < interimArray1.length; i++) {
console.log(interimArray1[i]);
}
}
var arr = [1, 2, 3, 4, 5, 6];
var num = 4;
reverseArray(num, arr);
You could use something like this.
function reverseArray(n, arrIn) {
// Splice splits the array in 2 starting at 0 index going n long
var arrOut = arrIn.splice(0,n);
// reverse is pretty straight forward
arrOut = arrOut.reverse();
// Concat joins the two together
return arrOut.concat(arrIn);
}

JavaScript -- search for array values in object

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(','));

Side effect/ changing global varaibles that pass into a function

Forgive me if this question has been asked, but I can't seem to find it.
I am attempting to create an array and reverse it (without using reverse)
This bit of code works perfect:
function reverseArrayInPlace(array) {
for (var i = 0; i < Math.floor(array.length / 2); i++) {
var old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]
As you can see, it takes an in an array, does some logic, and returns the same altered array.
Although, it doesn't make sense to me why this code doesn't work:
var some_array = [6,7,8,9,10];
function reverseArrayInPlace(array) {
var replacement_array = [];
for (var i = 0; i < some_array.length; i++)
replacement_array.unshift(array[i])
array = replacement_array;
return array;
}
reverseArrayInPlace(some_array);
console.log(some_array);
// → [ 6, 7, 8, 9, 10 ]
This code also takes in an array, does some logic (and assignment) and returns an array back. Why doesn't it alter the global variable like the first one? Is there any way to change it so that it can?
Ok,you need this:
function reverseArrayInPlace(array) {
replacement_array = [];
for (var i = 0; i <array.length; i++)
{
replacement_array.unshift(array[i])
}
for(var i = 0; i <array.length; i++){
array[i]=replacement_array[i]
}
return array;
}
some_array = [6,7,8,9,10];
reverseArrayInPlace(some_array)
console.log(some_array)
Replace the variable's content will work.
Stepping through the code:
function reverseArrayInPlace(array) {
var replacement_array = [];
for (var i = 0; i < some_array.length; i++)
replacement_array.unshift(array[i])
At this point you have created a new array that's the reverse of the original array.
array = replacement_array;
Assigning a new value to array will not alter the original array; only mutable array methods or element dereferencing can effect that.
return array;
}
You're returning the new array here, so you can perform an assignment outside of the function:
some_array = reverseArrayInPlace(some_array);
console.log(some_array);
However, that no longer qualifies as modifying an array in-place; you can use unshift() and splice() though:
for (var i = 1, n = array.length; i < n; ++i) {
array.unshift(array.splice(i, 1)[0]);
}
To affect the global directly:
var some_array = [6,7,8,9,10];
function reverseArrayInPlace(array) {
var replacement_array = [];
for (var i = 0; i < array.length; i++)
replacement_array.unshift(array[i]);
for (var i = 0; i < array.length; i++)
array[i] = replacement_array[i];
}
reverseArrayInPlace(some_array);
alert(some_array);
You don't need to return array.

Passing an array to a function that has a loop in Javascript

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

Categories