Related
I need to find first two numbers and show index like:
var arrWithNumbers = [2,5,5,2,3,5,1,2,4];
so the first repeated number is 2 so the variable firstIndex should have value 0. I must use for loop.
var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var firstIndex
for (i = numbers[0]; i <= numbers.length; i++) {
firstIndex = numbers[0]
if (numbers[i] == firstIndex) {
console.log(firstIndex);
break;
}
}
You can use Array#indexOf method with the fromIndex argument.
var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
// iterate upto the element just before the last
for (var i = 0; i < numbers.length - 1; i++) {
// check the index of next element
if (numbers.indexOf(numbers[i], i + 1) > -1) {
// if element present log data and break the loop
console.log("index:", i, "value: ", numbers[i]);
break;
}
}
UPDATE : Use an object to refer the index of element would make it far better.
var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11],
ref = {};
// iterate over the array
for (var i = 0; i < numbers.length; i++) {
// check value already defined or not
if (numbers[i] in ref) {
// if defined then log data and brek loop
console.log("index:", ref[numbers[i]], "value: ", numbers[i]);
break;
}
// define the reference of the index
ref[numbers[i]] = i;
}
Many good answers.. One might also do this job quite functionally and efficiently as follows;
var arr = [2,5,5,2,3,5,1,2,4],
frei = arr.findIndex((e,i,a) => a.slice(i+1).some(n => e === n)); // first repeating element index
console.log(frei)
If might turn out to be efficient since both .findIndex() and .some() functions will terminate as soon as the conditions are met.
You could use two for loops an check every value against each value. If a duplicate value is found, the iteration stops.
This proposal uses a labeled statement for breaking the outer loop.
var numbers = [1, 3, 6, 7, 5, 7, 6, 6, 4, 9, 10, 2, 11],
i, j;
outer: for (i = 0; i < numbers.length - 1; i++) {
for (j = i + 1; j < numbers.length; j++) {
if (numbers[i] === numbers[j]) {
console.log('found', numbers[i], 'at index', i, 'and', j);
break outer;
}
}
}
Move through each item and find if same item is found on different index, if so, it's duplicate and just save it to duplicate variable and break cycle
var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var duplicate = null;
for (var i = 0; i < numbers.length; i++) {
if (numbers.indexOf(numbers[i]) !== i) {
duplicate = numbers[i];
break; // stop cycle
}
}
console.log(duplicate);
var numbers = [7, 5, 7, 6, 6, 4, 9, 10, 2, 11];
var map = {};
for (var i = 0; i < numbers.length; i++) {
if (map[numbers[i]] !== undefined) {
console.log(map[numbers[i]]);
break;
} else {
map[numbers[i]] = i;
}
}
Okay so let's break this down. What we're doing here is creating a map of numbers to the index at which they first occur. So as we loop through the array of numbers, we check to see if it's in our map of numbers. If it is we've found it and return the value at that key in our map. Otherwise we add the number as a key in our map which points to the index at which it first occurred. The reason we use a map is that it is really fast O(1) so our overall runtime is O(n), which is the fastest you can do this on an unsorted array.
As an alternative, you can use indexOf and lastIndexOf and if values are different, there are multiple repetition and you can break the loop;
function getFirstDuplicate(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i]))
return arr[i];
}
}
var arrWithNumbers = [2, 5, 5, 2, 3, 5, 1, 2, 4];
console.log(getFirstDuplicate(arrWithNumbers))
var numbers = [1, 3, 6, 7, 5, 7, 6, 6, 4, 9, 10, 2, 11]
console.log(getFirstDuplicate(numbers))
I have the same task and came up with this, pretty basic solution:
var arr = [7,4,2,4,5,1,6,8,9,4];
var firstIndex = 0;
for(var i = 0; i < arr.length; i++){
for( var j = i+1; j < arr.length; j++){
if(arr[i] == arr[j]){
firstIndex = arr[i];
break;
}
}
}
console.log(firstIndex);
First for loop takes the first element from array (number 7), then the other for loop checks all other elements against it, and so on.
Important here is to define j in second loop as i+1, if not, any element would find it's equal number at the same index and firstIndex would get the value of the last one after all loops are done.
To reduce the time complexity in the aforementioned answers you can go with this solution:
function getFirstRecurringNumber(arrayOfNumbers) {
const hashMap = new Map();
for (let number of arrayOfNumbers) { // Time complexity: O(n)
const numberDuplicatesCount = hashMap.get(number);
if (numberDuplicatesCount) {
hashMap.set(number, numberDuplicatesCount + 1);
continue;
}
hashMap.set(number, 1); // Space complexity: O(n)
}
for (let entry of hashMap.entries()) { // Time complexity: O(i)
if (entry[1] > 1) {
return entry[0];
}
}
}
// Time complexity: O(n + i) instead of O(n^2)
// Space complexity: O(n)
Using the code below, I am able to get just the first '5' that appears in the array. the .some() method stops looping through once it finds a match.
let james = [5, 1, 5, 8, 2, 7, 5, 8, 3, 5];
let onlyOneFives = [];
james.some(item => {
//checking for a condition.
if(james.indexOf(item) === 0) {
//if the condition is met, then it pushes the item to a new array and then
//returns true which stop the loop
onlyOneFives.push(item);
return james.indexOf(item) === 0;
}
})
console.log(onlyOneFives)
Create a function that takes an array with numbers, inside it do the following:
First, instantiate an empty object.
Secondly, make a for loop that iterates trough every element of the array and for each one, add them to the empty object and check if the length of the object has changed, if not, well that means that you added a element that already existed so you can return it:
//Return first recurring number of given array, if there isn't return undefined.
const firstRecurringNumberOf = array =>{
objectOfArray = {};
for (let dynamicIndex = 0; dynamicIndex < array.length; dynamicIndex ++) {
const elementsBeforeAdding = (Object.keys(objectOfArray)).length;0
objectOfArray[array[dynamicIndex]] = array[dynamicIndex]
const elementsAfterAdding = (Object.keys(objectOfArray)).length;
if(elementsBeforeAdding == elementsAfterAdding){ //it means that the element already existed in the object, so it didnt was added & length doesnt change.
return array[dynamicIndex];
}
}
return undefined;
}
console.log(firstRecurringNumberOf([1,2,3,4])); //returns undefined
console.log(firstRecurringNumberOf([1,4,3,4,2,3])); //returns 4
const arr = [1,9,5,2,3,0,0];
const copiedArray = [...arr];
const index = arr.findIndex((element,i) => {
copiedArray.splice(0,1);
return copiedArray.includes(element)
})
console.log(index);
var addIndex = [7, 5, 2, 3, 4, 5, 7,6, 2];
var firstmatch = [];
for (var i = 0; i < addIndex.length; i++) {
if ($.inArray(addIndex[i], firstmatch) > -1) {
return false;
}
firstmatch.push(addIndex[i]);
}
I am rather new to JS and I was working on a problem that asked to split an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array.
I got the problem to work right for all test cases but it suggested using the array `push()` method. I tried it multiple times and couldn't ever get it to work right. I think I was getting messed up with arrays being by reference. I eventually declared a new Array for each element. I went with a more classic deep copy each element at a time. I Didn't go back and try the `push()` method again. There has to be a more efficient way to do this. I want to write good code. Would love to see better versions please.
Thanks!
function chunk(arr, size) {
var group = 0;
var counter = 0;
var even = false;
var odd = false;
if (arr.length % size === 0) {
group = arr.length / size;
even = true;
} else {
group = Math.ceil(arr.length / size);
odd = true;
}
var newArr = new Array(group);
for (var i = 0; i < group; i++) {
newArr[i] = new Array(size);
}
for (i = 0; i < group; i++) {
for (var j = 0; j < size && counter < arr.length; j++) {
newArr[i][j] = arr[counter++];
}
}
return newArr;
}
chunk(['a', 'b', 'c', 'd'], 2);
Using Array.prototype.slice, the function can be written in a shorter way:
function chunk(array, size) {
var result = []
for (var i=0;i<array.length;i+=size)
result.push( array.slice(i,i+size) )
return result
}
You can try the slice method from the Array object. Here's an idea on how to use it.
var arr = [1, 2, 3, 4, 5, 6];
var newArr = [];
newArr.push(arr.slice(0, arr.length / 2));
newArr.push(arr.length / 2, arr.length);
This is just an shallow implementation but you can use the same concept inside a better written function.
Here's an example function:
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
function toChunks(arr, size) {
var i = 0,
chunks = [];
for (; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size););
}
return chunks;
}
toChunks(arr, 2);
This is a 2 step problem:
1.) I am trying to 'double' the contents of one array (original Array), save it in a new array (Doubled Array).
2.) Then assign those two arrays to an Object with 2 attributes.
New Object
Orginal Numbers
Doubled Numbers
This is what I have so far, what am I doing wrong?
var numbers = [8, 12, 5, 2, 5, 7];
var doubledNumbers = [];
function doubled(arr){
for (var i = 0; i < arr.length; i ++){
var dub = arr[i];
var dubb = dub*2;
doubledNumbers.push(dubb);
}
}
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: doubled(numbers)
};
console.log(collectionNumbers);
The best way to do this in Javascript is using the map function:
var doubledNumbers = numbers.map(n => n*2);
The argument to map is the function that it uses to transform the elements in the first array into the elements in the second array. It is a tremendously useful method.
To answer your original question, the reason you were seeing undefined in collectionNumbers is because you forgot to return doubledNumbers in your function (and functions by default return undefined.
var numbers = [8, 12, 5, 2, 5, 7];
var doubledNumbers = [];
function doubled(arr){
var doubledNumbers = [];
for (var i = 0; i < arr.length; i ++){
var dub = arr[i];
var dubb = dub*2;
doubledNumbers.push(dubb);
}
return doubledNumbers;
}
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: doubled(numbers)
};
console.log(collectionNumbers);
What's wrong with your current code, is that your doubled function is returning nothing (which means it's returning undefined).
A better function would look like this:
function doubled (arr) {
var doubled = [];
for (var i = 0; i < arr.length; i++) {
doubled.push(arr[i] * 2);
}
return doubled;
}
However, an even better solution would be to just do this:
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: numbers.map(function (n) { return n * 2; })
};
.map is awesome.
Your whole routine can be simplified to
var numbers = [8, 12, 5, 2, 5, 7];
var collectionNumbers = {
orginialNumbers: numbers,
doubledNumbers: numbers.map(function(n) { return n*2; })
};
console.log(collectionNumbers);
using Array.map to create a new array with the doubled numbers
using Array.from, you can double and return new array
let inputArray = [9,8,7,3,2]
let outputArray = Array.from(inputArray, x => x *2) // creates new array
console.log(outputArray)
If I have an array which is 'dynamic', e.g:
var xArray = [2,4,5,5,6,7,8,9,9,8,7,7,6,6,6]
I need to find the closest number (in terms of INDEX) to the last entry, which is not equal to the last entry (in terms of NUMBER)
Kind of hard to explain! So in the case of the array above, the last entry is 6. I'm looking for the closest entry which is different to 6 (could be higher or lower value). in this case it would be
xArray[11] //7
so at the moment I have:
var lastX = xArray[xArray.length -1],
prevX = ?????
Something like :
function diff(arr) {
var a = arr.slice(), last = a.pop(), nxt = a.pop();
while (last == nxt && a.length) nxt = a.pop();
return nxt;
}
FIDDLE
call it like
var diff = diff(xArray);
Try
var xArray = [2, 4, 5, 5, 6, 7, 8, 9, 9, 8, 7, 7, 6, 6, 6]
var index = xArray.length - 1,
num = xArray[index];
while (--index >= 0 && xArray[index] == num);
console.log(index)
//here num will be 11
Demo: Fiddle
Try this,
var xArray = [2,4,5,5,6,7,8,9,9,8,7,7,6,6,6];
var xChangeDetector = null;
for(var I=xArray.length-1; I>=0 ; I--)
{
if(xChangeDetector == null)
{
xChangeDetector = xArray[I];
}
else if(xChangeDetector != xArray[I])
{
xChangeDetector = xArray[I];
break;
}
}
alert(xChangeDetector);
DEMO
function firstDifferent(arr) {
for (var i=arr.length-2; i>=0; i--) {
if (arr[i] != arr[arr.length - 1])
return i;
}
}
var xArray = [2,4,5,5,6,7,8,9,9,8,7,7,6,6,6];
var different = firstDifferent(xArray);
A functional solution could be this one:
var array = [2,4,5,5,6,7,8,9,9,8,7,7,6,6,6]
var lastIndex = array.reduce(function(acc,item,index,arr){
return item !== arr[acc] ? index : acc
}, 0) -1;
console.log(lastIndex);
It is not as efficient as the others because it needs to iterate through the entire array.
Suppose I have an array:
var ay=[0,1,2,3,4,5,6,7,8,9];
Now I want to get two array:
var ay1=[0,2,4,6,8];
var ay2=[1,3,5,7,9];
What is efficient way?
Update:
I know the simple loop and modulo operator method(as elclanrs said) like this:
var ay1=[],ay2=[];
for(var i=0,len=ay.length;i++){
if(i%2==0){
ay2.push(ay[i]);
} else
ay1.push(ay[i]);
}
But I just wonder if there is any other efficient or cool way I do not know yet.
That is why I ask this simple question. I am not asking how to do , I am asking how to do better if possible!
So I do not think this post deserved the down-votes.
Let's say we generalize this problem a bit. Instead of just splitting an array's alternating elements into two arrays, why not allow for the array to be split in the same way into three, four, or more individual arrays?
It turns out it's about as easy to allow for any number of arrays as it is to do just two.
Think of the array like a rope made up of strands, and whatever number of strands you have in the rope, you want to unravel it. You could do it like this:
// "Unravel" an array as if it were a rope made up of strands, going
// around the rope and pulling off part of each strand one by one.
// 'rope' is the array and 'count' is the number of strands.
// Return an array of arrays, where the outer array has length 'count'
// and the inner arrays represent the individual strands.
function unravel( rope, count ) {
// Create each strand
var strands = [];
for( var i = 0; i < count; i++ ) {
strands.push( [] );
}
// Unravel the rope into the individual strands
for( var i = 0, n = rope.length; i < n; i++ ) {
strands[ i % count ].push( rope[i] );
}
return strands;
}
var rope = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
var s = unravel( rope, 2 );
console.log( s[0], s[1] );
var s = unravel( rope, 3 );
console.log( s[0], s[1], s[2] );
var s = unravel( rope, 5 );
console.log( s[0], s[1], s[2], s[3], s[4] );
This logs:
[0, 2, 4, 6, 8] [1, 3, 5, 7, 9]
[0, 3, 6, 9] [1, 4, 7] [2, 5, 8]
[0, 5] [1, 6] [2, 7] [3, 8] [4, 9]
Note that in the second case (count=3) one of the strands is longer than the other two—which is to be expected since 10 is not evenly divisible by 3.
Why not use a modulus function?
for (var i = 0; i < ay.length; i++) {
if (i%2 == 0)
{
ay1[i] = ay[i];
}
else
{
ay2[i] - ay[i];
}
}
var ay=[0,1,2,3,4,5,6,7,8,9];
var ay1 = [];
var ay2 = [];
for (var i = 0; i < ay.length; i++)
if (i % 2) ay2.push(ay[i]);
else ay1.push(ay[i]);
console.log(ay1, ay2);
http://jsfiddle.net/MPAAC/
var ay1=new Array();
var ay2=new Array();
for (var i = 0, len = ay.length; i < len; i++) {
//Check the i is odd or even
//insert any one of the array
}
Why not use the array's filter method?
var ay = [0,1,2,3,4,5,6,7,8,9];
var odds = ay.filter(function(val){ return val % 2 === 1; });
var evens = ay.filter(function(val){ return val % 2 === 0; });
With a shim from the above link being available if you need to support IE8
Here's one way:
var ay = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var ay1 = [];
var ay2 = [];
for(var i = 0; i < ay.length; i++) {
if(i % 2 == 0) {
ay1.push(ay[i]);
}else{
ay2.push(ay[i]);
}
}
funciton isEven(x) {
return x % 2 == 0;
}
function isOdd(x) {
return ! isEven(x);
}
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
arrEven = arr.filter(isEven),
arrOdd = arr.filter(isOdd);
Here is a variant, just because I can. Is it "the most efficient"? Heck no; but it has the same bounds - O(1) for a constant-sized number of result lists.
It's cool and super flexible - it's really just a "partition" variant that can unzip to n (possibly non-distinct) sequences. Most other answers given are all based on a specialized partition implementation that doesn't utilize a HoF, so I consider this superior in that aspect ;-) It should be a good exercise to work through how this works.
function unzip(arr) {
var conds = Array.prototype.slice.call(arguments, 1);
// Requires ES5 or a shim for `Array.map`.
var res = conds.map(function () { return [] });
for (var i = 0; i < arr.length; i++) {
for (var k = 0; k < conds.length; k++) {
if (conds[k](i, arr[i])) {
res[k].push(arr[i]);
}
}
}
return res;
}
r = unzip([0,1,2,3,4],
function (i) { return !(i % 2) }, // even
function (i) { return i % 2 }); // odd
alert(r[0] + " || " + r[1]);
If underscore.js is already being used (why not?) then a groupBy approach can be used.