How to find the index of the first duplicate in array? - javascript

I need to find the index of the first duplicated number in an array and assign it to an empty variable using only for loop
Thanks in advance
i have tried many logical operators.
var findIndex;
var arrWithNumbers = [2, 4, 5, 2, 6, 5, 1, 2, 4, 8]; //-----> it should give result console.log(findIndex) // 0
var arrWithNumbers = [3, 4, 5, 2, 6, 5, 1, 2, 4, 8]; //-----> it should give result console.log(findIndex) // 1
var arrWithNumbers = [2, 4, 5, 2, 6, 5, 1, 2, 4, 8];
var firstIndex = null;
for (var i = 0; i < arrWithNumbers.length; i++) {
if (arrWithNumbers[i] === i) {
firstIndex = arrWithNumbers.indexOf(i);
break;
}
}
console.log(firstIndex);
what I expect:
var arrWithNumbers = [2, 4, 5, 2, 6, 5, 1, 2, 4, 8]; //-----> it should give result console.log(findIndex) // 0
var arrWithNumbers = [3, 4, 5, 2, 6, 5, 1, 2, 4, 8]; //-----> it should give result console.log(findIndex) // 1
//what i have
var arrWithNumbers = [2, 4, 5, 2, 6, 5, 1, 2, 4, 8];
var firstIndex = null;
for (var i = 0; i < arrWithNumbers.length; i++) {
if (arrWithNumbers[i] === i) {
firstIndex = arrWithNumbers.indexOf(i);
break;
}
}
console.log(firstIndex); // 2

One option you have is to have a variable that contains all the count of the number, you can do this by using reduce
var arrWithNumbers = [2, 4, 5, 2, 6, 5, 1, 2, 4, 8];
var firstIndex = null;
var numberCount = arrWithNumbers.reduce((c, v) => (c[v] = (c[v] || 0) + 1, c), {});
for (var i = 0; i < arrWithNumbers.length; i++) {
if (numberCount[arrWithNumbers[i]] > 1) {
firstIndex = i;
break;
}
}
console.log(firstIndex);
Another option is using lastIndexOf. If the current index is not the same as the lastIndexOf value, means that it has duplicate and break the loop.
var arrWithNumbers = [3, 2, 4, 5, 2, 6, 5, 1, 2, 4, 8];
var firstIndex = null;
for (var i = 0; i < arrWithNumbers.length; i++) {
if (i !== arrWithNumbers.lastIndexOf(arrWithNumbers[i])) {
firstIndex = i;
break;
}
}
console.log(firstIndex);

You could take a hash table for visited values and store their indices. Then you need only the check if the hash property is set and return the index.
This approach works with a single loop and exits early on the first found same value.
function findIndex(array) {
var indices = Object.create(null),
i, value;
for (i = 0; i < array.length; i++) {
value = array[i];
if (value in indices) return indices[value];
indices[value] = i;
}
}
console.log(findIndex([2, 4, 5, 2, 6, 5, 1, 2, 4, 8])); // 0
console.log(findIndex([3, 4, 5, 2, 6, 5, 1, 2, 4, 8])); // 2

You can use a nested for loop, to check all values after index i in your array :
var arrWithNumbers = [2, 4, 5, 2, 6, 5, 1, 2, 4, 8];
var firstIndex = null;
for (var i = 0; i < arrWithNumbers.length; i++) {
value_i = arrWithNumbers[i]
// loop through the next items of the array
for (var j = i+1 ; j < arrWithNumbers.length; j++) {
if (value_i == arrWithNumbers[j]) {
firstIndex = i;
break;
}
}
if (firstIndex !== null) {
// we found our firstIndex, quit the main loop
break;
}
}
console.log(firstIndex)

Related

Finding the diagonal sum of 2D array

const diagonalSum = function (arr) {
var length=arr.length -1;
var sum=0;
for(let i=0;i<arr.length;i++){//1<3
sum+= arr[i][i]+arr[i][length-i]//[1][0]+
}
return sum;
};
tried this , but 2nd and 3rd test cases are not getting passed. Any other logic?
const diagonalSum = function (arr) {
var length=arr.length -1;
var sum=0;
for(let i=0;i<arr.length;i++){//1<3
sum+= arr[i][i]+arr[i][length-i]//[1][0]+
}
return sum;
};
searching any other logic
This will work for you.
// An efficient Javascript program to find
// sum of diagonals
function printDiagonalSums(mat,n)
{
let principal = 0, secondary = 0;
for (let i = 0; i < n; i++) {
principal += mat[i][i];
}
document.write("Principal Diagonal:"
+ principal+"<br>");
}
// Driver code
let a = [[ 1, 2, 3, 4, 5],
[5, 6, 7, 8, 5 ],
[ 1, 2, 3, 4, 5 ],
[ 5, 6, 7, 8, 5],
[ 5, 6, 7, 8, 5]];
printDiagonalSums(a, 5);

how could i write a for loop that adds up all the numbers in the array to the totalSnacksEaten variable in javascript

let snacksEatenPerDay = [3, 2, 5, 6, 1, 2, 2, 4, 8, 2, 5, 3, 3, 1];
let totalSnacksEaten = 0;
for(let i = 0; i<=snacksEatenPerDay ; i++)
totalSnacksEaten = totalSnacksEaten +i
console.log(totalSnacksEaten);
i want to modify my code so i could have a result to know the sum of the array in the variable
Hope you do well in javascript.
let snacksEatenPerDay = [3, 2, 5, 6, 1, 2, 2, 4, 8, 2, 5, 3, 3, 1];
let totalSnacksEaten = 0;
for(let i = 0; i<snacksEatenPerDay.length ; i++){
totalSnacksEaten = totalSnacksEaten + snacksEatenPerDay[i]
}
console.log(totalSnacksEaten);
This will work for you...
let snacksEatenPerDay = [3, 2, 5, 6, 1, 2, 2, 4, 8, 2, 5, 3, 3, 1];
let totalSnacksEaten = 0;
for(var i = 0; i < snacksEatenPerDay.length ; i++){
totalSnacksEaten += snacksEatenPerDay[i];
}
console.log(totalSnacksEaten);
I recommend you study the basics of javascript and array concept.
let snacksEatenPerDay = [3, 2, 5, 6, 1, 2, 2, 4, 8, 2, 5, 3, 3, 1];
let totalSnacksEaten = 0;
for(let i = 0; i<snacksEatenPerDay.length ; i++){
totalSnacksEaten = totalSnacksEaten + snacksEatenPerDay[i]
}
console.log(totalSnacksEaten);
Use Array.reduce(), which takes a callback function that is executed upon each iteration of the array and reduces the array to a single output value. That callback function will automatically be passed several arguments, but the first two (accumulator and current value) are all you need for this:
let snacksEatenPerDay = [3, 2, 5, 6, 1, 2, 2, 4, 8, 2, 5, 3, 3, 1];
let totalSnacksEaten = snacksEatenPerDay.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
});
console.log(totalSnacksEaten );
You can do this a few ways, but you might want to read up on javascript's reduce function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Here's an example:
// ES5 way
let snacksEatenPerDay = [3, 2, 5, 6, 1, 2, 2, 4, 8, 2, 5, 3, 3, 1];
let totalSnacksEaten = snacksEatenPerDay.reduce(function(acc, value) {
return acc + value;
}, 0);
console.log(totalSnacksEaten);
// ES6 way
const reducer = (accumulator, currentValue) => accumulator + currentValue;
let totalSnacksEatenReducer = snacksEatenPerDay.reduce(reducer);
console.log(totalSnacksEatenReducer);

how to check if 2 rows are symmetrical?

i have 2 rows that i need to check in java script if they are symmetrical
row 1 [2, 7, 9, 9, 7, 2] row 2 [5 7 3 3 7 5] how would you do it ?
var r = [[5, 7, 3, 3, 7, 5], [2, 7, 9, 9, 7, 2]];
function isSymmetric(r) {
// convert to object
var rel = {}
for (var i = 0; i < r.length; i++) {
if (!(r[i][0] in rel)) rel[r[i][0]] = {};
rel[r[i][0]][r[i][1]] = true;
}
// Test to see if opposite relation is in object
for (var a in rel) {
for (var b in rel[a]) {
if (!rel[b] || !rel[b][a]) return false;
}
}
return true;
}
console.log(isSymmetric(r));
You could do something like this:
let isSymmetric = arr => {
for(var i=0; i < arr.length; i++) {
if(arr[i] !== arr[arr.length - (i+1)])
return false
}
return true
}
console.log(isSymmetric([5, 7, 3, 3, 7, 5]))
console.log(isSymmetric([1, 7, 9, 9, 7, 2]))
The idea is to loop through the array and for each index compare with its "sibling" from the right side. If one is not the same them return false.
You can start from 0th index and compare the value with its symmetric pair (length - 1 - i), and if they are not same then return false. You should stop at the middle length / 2:
let values = [
[5, 7, 3, 3, 7, 5],
[2, 7, 9, 1, 9, 7, 2],
[5, 7, 3, 3, 7, 1]
];
function isSymmetric(arr) {
for (let i = 0; i < arr.length / 2; i++) {
if (arr[i] !== arr[arr.length - 1 - i]) {
return false;
}
}
return true;
}
values.forEach(v =>
console.log(isSymmetric(v))
);
Use lodash.
var row = [2, 7, 9, 9, 7, 2];
var halves = _.chunk(row, _.ceil(row.length / 2));
var result = _.isEqual(halves[0], _.reverse(halves[1]));

Looping through two (different lengthed) arrays to produce an alternating output

What is an efficient way of looping through two arrays to produce an alternating output? In JavaScript.
If I have two arrays like this:
var oddNumbers = [1, 3, 5, 7, 9]
var evenNumbers = [2, 4, 6, 8, 10, 12, 14]
NB: The arrays may not be the same length
How can I get the following output?
Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14
I would have thought this would work:
if (oddNumber.length > evenNumbers.length) {
var large = oddNumbers;
} else {
var large = evenNumbers;
}
for(var i = 0; i < large.length; i++){
if (evenNumbers.length >= i && oddNumbers.length >= i) {
console.log(oddNumbers[i] + ", " + evenNumbers[0]);
} elseif (evenNumbers.length >= i) {
console.log(evenNumbers[0]);
} else {
console.log(oddNumbers[0]);
}
}
But it's pretty messy, any better way of approaching this?
NOTE: These may not necessarily be in a numerical order, or in fact numbers
I would rather do it as follows if you just want to output them:
var oddNumbers = [1, 3, 5, 7, 9];
var evenNumbers = [2, 4, 6, 8, 10, 12, 14];
for (var i=0, j=0; i < oddNumbers.length || j < evenNumbers.length;) {
if (i < oddNumbers.length) {
console.log(oddNumbers[i++]);
}
if (j < evenNumbers.length) {
console.log(evenNumbers[j++]);
}
}
If you want to get the merge result as another array you can replace console.log with result.push to push result values on an array named result as follows:
var oddNumbers = [1, 3, 5, 7, 9];
var evenNumbers = [2, 4, 6, 8, 10, 12, 14];
var result = [];
for (var i=0, j=0; i < oddNumbers.length || j < evenNumbers.length;) {
if (i < oddNumbers.length) {
result.push(oddNumbers[i++]);
}
if (j < evenNumbers.length) {
result.push(evenNumbers[j++]);
}
}
console.log(result);
This way you iterate both arrays as long as one of them has an element that we haven't visited yet and also prevents iterating over the same index of same array twice. Please note that I used increment in if blocks to save 2 lines of code. You can also move them to the for loop since they won't break if statements.
var oddNumbers = [1, 3, 5, 7, 9];
var evenNumbers = [2, 4, 6, 8, 10, 12, 14];
var oLength = oddNumbers.length;
var eLength = evenNumbers.length;
var n = oLength > eLength ? oLength : eLength;
var rez=[];
for(i=0;i<n;i++){
if (i< oLength) rez.push(oddNumbers[i])
if (i<eLength) rez.push(evenNumbers[i])
}
console.log(rez);
var odd = ["A", "C","E","G"];
var even = ["B","D","F"];
var rez=[];
for(i=0;i<(odd.length > even.length ? odd.length : even.length);i++){
if (i< odd.length) rez.push(odd[i])
if (i<even.length) rez.push(even[i])
}
console.log(rez);
The following function accepts two arrays and returns their interleaved values as a new array:
function interleaveArrays(a, b) {
var array = [],
limit = a.length >= b.length ? a.length : b.length;
index = 0;
while (index < limit) {
a[index] && array.push(a[index]);
b[index] && array.push(b[index]);
index += 1;
}
return array;
}
Calling the function like so:
var oddNumbers = [1, 3, 5, 7, 9],
evenNumbers = [2, 4, 6, 8, 10, 12, 14];
console.log(interleaveArrays(oddNumbers, evenNumbers));
Yields:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14 ]
You can then output this in your preferred manner; e.g:
var interleaved = interleaveArrays(oddNumbers, evenNumbers);
// as a loop
interleaved.forEach(function (n) {
console.log(n);
})
// or as a string
console.log(interleaved.join(', '));
// etc.
Hope this helps :)
I'd do something like this.
large = (oddNumber.length >= evenNumbers.length) ? oddNumbers : evenNumbers;
small = (oddNumber.length < evenNumbers.length) ? oddNumbers : evenNumbers;
for(var i = 0; i < large.length; i++){
if(small.length <= i + 1){
console.log(small[i] + ", "+ large[i]);
}
else {
console.log(large[i]);
}
}
A long-hand example of how it can be done. The code can be shrunk for a final solution. The basic principle I'm using is to even out the lengths to take care of the alternating then tag on the tail
var oddNumbers = [1, 3, 5, 7, 9];
var evenNumbers = [2, 4, 6, 8, 10, 12, 14];
var oLength = oddNumbers.length;
var eLength = evenNumbers.length;
var oTemp, eTemp, remainder;
if(oLength > eLength) {
eTemp = evenNumbers;
oTemp = oddNumbers.slice(0, eLength);
remainder = oddNumbers.slice(eLength);
} else if (eLength > oLength) {
eTemp = evenNumbers.slice(0, oLength);
oTemp = oddNumbers;
remainder = evenNumbers.slice(oLength);
} else {
eTemp = evenNumbers;
oTemp = oddNumbers;
remainder = [];
}
var final = [];
for(var i=0; i < eTemp.length; i++) {
final.push(oTemp[i]);
final.push(eTemp[i]);
}
final = final.concat(remainder);
alert(final);
I would simply merge the two array and sort it
var oddNumbers = [1, 3, 5, 7, 9];
var evenNumbers = [2, 4, 6, 8, 10, 12, 14];
var mergedArr=oddNumbers.concat(evenNumbers );
console.log(mergedArr.sort(function(a,b){return a-b;}));
See No loop.. No hassle. Very Simple
There will be an extra , on the screen. Add an if statement if you don't want that
for(var i = 0; i < large.length; i++){
if(i<evenNumbers.length)
console.log(evenNumbers[i]+",");
if(i<oddNumber.length)
console.log(evenNumbers[i]+",");
}
try this it will work always either number Array or String Array:
var oddNumber = [1, 3, 5, 7, 9]
var evenNumber = [2, 4, 6, 8, 10, 12, 14]
var margedNumbers = oddNumber.concat(evenNumber);
console.log("before: "+margedNumbers);
margedNumbers.sort(function(a, b){return a-b})
console.log("after: "+margedNumbers)
My solution
var oddNumbers = [1, 3, 5, 7, 9]
var evenNumbers = [2, 4, 6, 8, 10, 12, 14]
var extraElements = (oddNumbers.length > evenNumbers.length) ? oddNumbers.slice(evenNumbers.length) : evenNumbers.slice(oddNumbers.length);
var finalArr = [];
var small = (oddNumbers.length < evenNumbers.length) ? oddNumbers : evenNumbers;
small.forEach((each, index) => {
// merge elements in desired order
finalArr.push(oddNumbers[index]);
finalArr.push(evenNumbers[index]);
})
finalArr = finalArr.concat(extraElements);
alert(finalArr);
Extract the extra elements which makes both array of same length. Then, in a simple iteration, push elements from both array with same index.

How to create a proper sum function?

I'm trying to create a sum function. When I run it through two different arrays (with same values), it's giving me different results. I can't really tell where I did wrong. It seems when I'm generating the array using the 'range' function, it's looping twice.
var myArr = [];
var tempArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function range(start, end) {
for (i = start; i <= end; i++) {
myArr.push(start);
start = start + 1;
}
return myArr;
}
function sum(arr) {
var sumArr = 0;
for (i = 0; i < arr.length; i++) {
sumArr = sumArr + arr[i];
//console.log(sumArr);
}
return sumArr;
}
console.log(range(1, 10)); //[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(tempArr); //[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(sum(range(1, 10))); //110
console.log(sum(tempArr)); //55
Any help would be appreciated. Thanks!
The reason is that var myArr = []; was a global variable. So pushed elements in the first console attempt will be there until they are cleared. You can use local variable in the function instead.
var tempArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function range(start, end) {
var myArr = [];
for (i = start; i <= end; i++) {
myArr.push(start);
start = start + 1;
}
return myArr;
}
function sum(arr) {
var sumArr = 0;
for (i = 0; i < arr.length; i++) {
sumArr = sumArr + arr[i];
//console.log(sumArr);
}
return sumArr;
}
console.log(range(1, 10)); //[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(tempArr); //[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(sum(range(1, 10))); //55
console.log(sum(tempArr)); //55
Using lodash :
You can use ._sum function.
var tempArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sum = _.sum(tempArr)
Don't forget to add the library if you want to use it.
<script src="https://cdn.jsdelivr.net/lodash/4.5.1/lodash.min.js"></script>
Demo

Categories