Get small element index till array length - javascript

I have to sort an array and want to get index so that I can sort another array on the basis of this index..
There are two array a and b I saved division of that array in third array that is sortDiv now I want index of small element so that I can sort a and b according to index..
Code is like
var a = [6, 7, 8, 9];
var b = [1, 2, 3, 4];
var sortA = [],
sortB = [],
sortDiv = [];
var div = a[0] / b[0];
for (var i = 0; i < a.length; i++) {
sortDiv.push(a[i] / b[i]);
}
var temp = sortDiv;
for (var i = 1; i < sortDiv.length; i++) {
var val = Math.min.apply(Math, temp);
var key = sortDiv.indexOf(val);
sortA.push(a[key]);
sortB.push(b[key]);
if (key > -1)
temp.splice(key, 1);
}
console.log(sortA + " " + sortB);
I got [9,8] for a and [4,3] for b..while I want a=[9,8,7,6] b=[1,2,3,4]
But splice is not a good option..I need a function that remove only element not an index..any idea please?
UPDATED
As problem is solved but I want to know that
Is it possible to remove element but not an index in array?

Try not removing element just replacing it with maximum element +1 and it will work fine here is the updated code
var a = [6, 7, 8, 9];
var b = [1, 2, 3, 4];
var sortA = [],
sortB = [],
sortDiv = [];
var div = a[0] / b[0];
for (var i = 0; i < a.length; i++) {
sortDiv.push(a[i] / b[i]);
}
console.log(sortDiv);
var temp = sortDiv;
var max = Math.max.apply(Math, temp); // here we find the maximum
max += 1;
for (var i = 1; i <= sortDiv.length; i++) {
var val = Math.min.apply(Math, temp);
console.log(val);
var key = sortDiv.indexOf(val);
sortA.push(a[key]);
sortB.push(b[key]);
temp[key] = max; // here we update the minimum with maximum+1
}
console.log(sortA + " " + sortB);

If the question is about using splice to remove an item based on the value and not the index, get the index, then use splice:
var a = ['a', 'b', 'c'];
a.splice(a.indexOf('b'), 1);
console.log(a); // ["a", "c"]

Related

Sort Array to 1st min, 1st max, 2nd min, 2nd max, etc

Write a JS program to return an array in such a way that the first element is the first minimum and the second element is the first maximum and so on.
This program contains a function which takes one argument: an array. This function returns the array according to the requirement.
Sample Input: array=[2,4,7,1,3,8,9]. Expected Output: [1,9,2,8,3,7,4].
const arrsort=(arr)=>{
return arr.sort(function(a, b){return a - b});
}
const test=(arr)=>{
arr=arrsort(arr);
var arr2=[];
var j=0;
var k=arr.length-1;
for (var i=0;i<arr.length-1;i++){
if(i%2===0){
arr2.push(arr[j]);
j++;
}
else{
arr2.push(arr[k]);
k--;
}
}
return arr2;
}
Instead of using two indices, you could shift and pop the values of a copy of the sorted array.
var array = [2, 4, 7, 1, 3, 8, 9]
const arrsort = arr => arr.sort((a, b) => a - b);
const test = (arr) => {
var copy = arrsort(arr.slice()),
result = [],
fn = 'pop';
while (copy.length) {
fn = { pop: 'shift', shift: 'pop' }[fn];
result.push(copy[fn]());
}
return result;
}
console.log(test(array));
You can first sort() the array in ascending order and then loop through half of the array. And push() the values at corresponding indexes.
let arr = [2,4,7,1,3,8,9];
function order(arr){
let res = [];
arr = arr.slice().sort((a,b) => a-b);
for(let i = 0; i < Math.floor(arr.length/2); i++){
res.push(arr[i],arr[arr.length - 1 - i]);
}
return arr.length % 2 ? res.concat(arr[Math.floor((arr.length - 1)/2)]) : res;
}
console.log(order(arr))
You could sort the array, then copy and reverse and push to another array
const a = [2,4,7,1,3,8,9];
a.sort();
const b = a.slice().reverse();
const res = [];
for (let i = 0; i < a.length; i++) {
if (res.length < a.length) res.push(a[i]);
if (res.length < a.length) res.push(b[i]);
}
console.log(res);
Or use a Set
const a = [2,4,7,1,3,8,9];
a.sort();
const b = a.slice().reverse();
const res = new Set();
a.forEach((e, i) => (res.add(e), res.add(b[i])));
console.log(Array.from(res));
There are many ways are available to do this. And my solution is one of themm i hope.
Find max and min value, push them into another array. And delete max, min from actual array.
let array=[2,4,7,1,3,8,9];
let finalArray = [];
let max, min;
for(let i = 0; i < array.length; i++) {
max = Math.max(...array);
min = Math.min(...array);
finalArray.push(min);
finalArray.push(max);
array = array.filter(function(el) {
return el != max && el != min;
})
}
console.log(finalArray);
After sorting array this would work
myarr = [1,2,3,4,5,6];
let lastindex = myarr.length-1;
for(let i = 1 ; i <= myarr.length/ 2; i = i+2) {
ele = myarr[i];
myarr[i] = myarr[lastindex];
myarr[lastindex] = ele;
lastindex--;
}
Final Output will be: [1, 6, 3, 5, 4, 2]
You can use two iterators after sorting your array, one goes ascending and the other goes descending, until they cross each other.
Here's the code:
const array = [2, 4, 7, 1, 3, 8, 9];
const test = arr => {
const result = [];
const sortedArr = array.sort((a, b) => a - b);
for (let i = 0, j = sortedArr.length - 1; i <= j; i++, j--) {
result.push(sortedArr[i]);
i == j || result.push(sortedArr[j]);
}
return result;
};
console.log(test(array));
You can easily achieve the result using two pointer algorithm
function getValue(arr) {
const result = [];
let start = 0,
end = arr.length - 1;
while (start < end) result.push(arr[start++], arr[end--]);
if (start === end) result.push(arr[start]);
return result;
}
const array = [2, 4, 7, 1, 3, 8, 9];
const sorted = array.sort();
console.log(getValue(sorted));

loop over array, but not every element

I would like to iterate over the array and getting an average from 5 next elements, not from the whole array. I try to do it by code bellow, but it doesn´t work. I appreciate any kind of help or suggestions.
function standardDeviation(array) {
let newArray = [];
for (let i = 0; i < array.length; i++) {
let tempArray = [];
const arrAvg = tempArray =>
tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
newArray += tempArray;
for (let j = array[i]; (j = array[i + 5]); i++) {
tempArray += array[j];
}
}
console.log(newArray);
return newArray;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
standardDeviation(arr);
You could slice a given array and take only five elements for getting an average.
function standardDeviation(array) {
const arrAvg = tempArray => tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
return array.map((_, i, a) => arrAvg(a.slice(i, i + 5)));
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(standardDeviation(arr));
You could try using the slice() function of array element.
// simulated loop index
var curr_index_pos = 3;
// entire array
var array_full = [1,2,3,4,5,6,7,8,9,10];
// array with 5 next values from "curr_index_pos"
var array_5 = array_full.slice(curr_index_pos,curr_index_pos+5);
var sum = 0;
for( var i = 0; i < array_5.length; i++ ) {
sum += parseInt( array_5[i] );
}
var avg = sum/array_5.length;
console.log("array_5", array_5);
// [4,5,6,7,8]
console.log("sum", sum);
// 30
console.log("avg", avg);
// 6

finding index of duplicates in an array in js

I have two arrays
arr1=[ 0, 1, 2, 0, 2 ];
arr2=[ 0, 0, 1, 2, 2 ];
I have to find index of elements of arr2 from arr1 and output array need to be like [0,3,1,2,4];
I have written a code but it works on array without duplicate`
var index = [];
for (i = 0; i <= arr2.length - 1; i++) {
index.push(arr1.indexOf(arr2[i]));
}
You need to search after the first index for the second element and same for all repeating elements(for third after index). You can specify fromIndex argument in Array#indexOf method to start the search at a specific index.
// use a reference object to specify from index for duplicate
var ref = {};
var index = [];
for (i = 0; i < arr2.length; i++) {
// specify from index from object, if not found set as 0
var i1 = arr1.indexOf(arr2[i], ref[arr2[i]] || 0);
// push the index
index.push(i1);
// specify from index for current element
ref[arr2[i]] = i1 + 1;
}
var ref = {};
var arr1 = [0, 1, 2, 0, 2],
arr2 = [0, 0, 1, 2, 2];
var ref = {};
var index = [];
for (i = 0; i < arr2.length; i++) {
var i1 = arr1.indexOf(arr2[i], ref[arr2[i]] || 0);
index.push(i1);
ref[arr2[i]] = i1 + 1;
}
console.log(index);
Using Array#map method to generate the index array.
var index = arr2.map(function(v, i) {
// get the index of the element, where specify from index to
// search after a certain index for repeating element
var i1 = arr1.indexOf(v, this[v] || 0);
// set reference of index
this[v] = i1 + 1;
// return index
return i1;
// set this argument as an object for from index reference
}, {});
var arr1 = [0, 1, 2, 0, 2],
arr2 = [0, 0, 1, 2, 2];
var index = arr2.map(function(v, i) {
var i1 = arr1.indexOf(v, this[v] || 0);
this[v] = i1 + 1;
return i1;
}, {});
console.log(index);
var arr1 = [ 0, 1, 2, 0, 2 ];
var arr2 = [ 0, 0, 1, 2, 2 ]
var index = [];
var hash = {};
for (i = 0; i < arr2.length; i++) {
var ind_temp;
if(arr2[i] in hash){
//console.log("here");
ind_temp = arr1.indexOf(arr2[i],hash[arr2[i]] + 1);
index.push(ind_temp);
hash[arr2[i]] = ind_temp;
}
else{
ind_temp = arr1.indexOf(arr2[i]);
index.push(ind_temp);
hash[arr2[i]] = ind_temp;
}
}
console.log(index);
You can look through the array and map it onto anther array, setting the first instance to undefined. Obviously this doesnt work if undefined is a value you could want to search for.
var zz = arr1.map(val => {
if (!val) return undefined
let ind = arr2.indexOf(val)
if (ind) arr2[ind] = undefined
return ind
})
If you have just positive numbers, try this
var temp = arr1.slice(0); //Clone arr1 to a temp Arr
var index = [];
arr2.forEach(item => {
let ind = temp.indexOf(item);
index.push(ind);
ind > -1 && (temp[ind] = -1);
})
console.log(index);
What you can do is iterate over arr2 and save found index from arr1 in variable, and if element of arr2 is equal to previous element in arr2 then compare from saved index + 1, for this you can use 2nd parameter of indexOf method.
var duplicate =[ 0, 1, 2, 0, 2 ];
var newiter =[ 0, 0, 1, 2, 2 ];
var indexArray = []; //RESULT ARRAY
var newiter = newiter.sort(); //IN CASE newiter IS NOT SORTED
var i = -1;
for(var j = 0; j<newiter.length; j++) {
// check if element from newiter is equal to previous , if not set i to -1
if(j > 0 && newiter[j] != newiter[j-1]) {
i = -1;
}
// get index from duplicate but start searching from i+1
i = duplicate.indexOf(newiter[j], i+1);
indexArray.push(i);
}
console.log(indexArray);

Finding addenth on array - JS

I created a function that will find pairs to add the two numbers that will be equal to the sum.
function findingSum(arr, sum){
var firstElement = [];
var difference = [];
var final = [];
var convertArr = arr.map(function(item){
return parseInt(item, 10);
});
for(var i = 0; i < convertArr.length; i++){
difference.push(sum - convertArr[i]); // subtracted sum from each convertArr item
if(difference[i] + convertArr[i] === sum){ // check if convertArr item was added to difference item === sum
firstElement.push(convertArr[i]); // if so add the convertArritem to the result array
}
if(firstElement[i] + convertArr[i] == sum){
final.push(firstElement[i], convertArr[i]);
}
}
return final;
}
var addNumbers = findingSum([3, 34, 4, 12, 5, 2], 9);
console.log(addNumbers); // --> [4, 5]
So what I did is that I try to get the difference of convertArr[i] and the sum and put them in a difference variable. Then I tried to see if adding difference[i] from the original array will give me the sum. If so I'll add them on firstElement array and try to add each value to the original array and finally push them along with it's addenth if the sum was attain. So when you add this two you'll get the sum.
For some reason my logic doesn't work and it does'nt push things on both firstElement and final array. Can anyone help me with this?>
You could use a hash table for visited values.
var findingSum = function (array, s) {
var a, i,
hash = Object.create(null);
for (i = 0; i < array.length; i++) {
a = array[i];
if (hash[s - a]) {
return [s - a, a];
}
if (!hash[a]) {
hash[a] = true;
}
}
};
console.log(findingSum([3, 34, 4, 12, 5, 2], 9)); // [4, 5]

Java Script - Adding null value to array, if the element is not present at particular index

Array length is 7
Original array
var arr = [2, 4, 6];
Needed array
arr = [null,null,2,null,4,null,6];
0 is not present in array so need to replace with null,
1 is not available replace with null and
2 is available so put 2 in new array so on..
You can use the splice() method on the array
var arr=[2,4,6];
var l = arr[arr.length-1];
for(var i=0; i<=l; i++){
if(arr[i] !== i){
arr.splice(i, 0, null);
}
}
Output : [null, null, 2, null, 4, null, 6]
This modifies the original array.
I will write a permanence case for all answers soon.
function createArrayFromArray(array, length) {
var new_array = new Array(length);
for (var i = 0; i < new_array.length; i++) {
new_array[i] = null;
}
for (var i = 0; i < array.length; i++) {
new_array[array[i]] = array[i];
}
return new_array;
}
console.log(createArrayFromArray(arr, 7)); //[null, null, 2, null, 4, null, 6]
You just need to find the max value in the array and then iterate from 0 to that max, checking each value to see if it was present in the source or not:
var arr = [2, 4, 6];
var max = Math.max.apply(Math, arr);
var result = [];
for (var i = 0; i <= max; i++) {
if (arr.indexOf(i) !== -1) {
result[i] = i;
} else {
result[i] = null;
}
}
Working demo: http://jsfiddle.net/jfriend00/c7p8mkqy/
As I asked in my comments, I'd like to know what problem you're actually trying to solve because it seems like both the original and the newly created data structures are inefficient structures that could probably use different form of data and work more efficiently. But, we can only help you make a wiser choice if you explain the actual problem, rather just your attempted solution.
Given you have the only input arr which you want to fill null inside. Try this:
var arr = [2, 4, 6];
var output = [];
while (arr.length>0){
var first = arr.splice(0,1);
while (output.length<first[0])
output.push(null);
output.push(first[0]);
}
// output should be [null,null,2,null,4,null,6];
Try:
var arr = [2, 4, 6];
var new_arr = [];
var i = 0;
while(i < 7){
var pos = arr.indexOf(i++);
new_arr.push(pos !== -1 ? arr[pos] : null)
}
document.write(JSON.stringify(new_arr, null, 4))
var arr = [2, 4, 6];
var result = new Array(7);
arr.forEach(function(a) { result[a] = a;});
Interesting quiz:
var arr = [2, 4, 6]
var n = 0
while(arr.length > n) {
if(arr[n] !== n) {
arr = arr.slice(0,n).concat(null, arr.slice(n))
}
n++
}
console.log(arr) // [null, null, 2, null, 4, null, 6]
This approach applies to array consists of random number of sorted integers.
var arr = [2, 4, 6];
var narr = (new Array(arr.sort()[arr.length-1]))
arr.map(function(v){
narr[v] = v;
});
for (var i = 0; i<narr.length; i++) narr[i]||(narr[i]=null);
console.log(narr);
Try splice():
var arr = [2, 4, 6];
var i = 0,
l = arr[arr.length - 1];
while (i < l) {
if(i !== arr[i])
arr.splice(i, 0, null);
i++;
}
console.log(arr); //[ null, null, 2, null, 4, null, 6 ]

Categories