Javascript sorting input values into an array - javascript

I have the below code which looks at hidden inputs with the class howmanyproducts.
$("#proddiv .howmanyproducts").each(function() {
var idval = $(this.id).val();
});
What I am trying to achieve is for each id get the value and sort the ids into an array based on their values.

You have to add both your ids and the corresponding values to an array, then to use the sort method of your array with an adapted compare function. Let say your values are number but are retrieved as string :
// Create a new empty array :
var ids = [];
$("#proddiv .howmanyproducts").each(function() {
var id = this.id;
var val = $(this.id).val();
// Store the id and the value:
ids.push([id, +val]);
});
// Sort the array in place, using the second element of each item
// ie. the value :
ids.sort(function(a, b) { return a[1] - b[1]; });
// Once sorted, make a new array with only the ids:
var result = ids.map(function(a,b) { return a[0] });
I used the traditional syntax, but note that it can be written more simply using arrow functions:
ids.sort((a,b) => a[1] - b[1]);
var result = ids.map((a,b) => a[0]);

var arrayOfValues = [];
$("#proddiv .howmanyproducts").each(function() {
arrayOfValues.push($(this).val());
}

Related

Can you pass an array of index numbers to the array push method instead of specifying each index in push specifically

I want to create a new 2D array from another 2D array retaining specific columns from the original array that are defined in a variable.
I have a working version that uses hardcoded values of which columns from the original array to retain but I need a version that uses a variable.
var data = [
[1,5,7,8,9,98,56],
[4,7,8,9,2,55,88],
[3,3,4,3,3,24,11]
];
var indexes2Keep = [0,2,6];
data.forEach(function(row) {
slicedData.push( [ row[2], row[4], row[6] ] );
});
Instead of having the columns hardcoded in the array push method how can I use the values of the variable indexes2Keep to give the same result.
thanks
Expected output is:
slicedData = [
[1,7,56],
[4,8,88],
[3,4,11]
];
You can use Array.map/Array.filter:
var data = [
[1,5,7,8,9,98,56],
[4,7,8,9,2,55,88],
[3,3,4,3,3,24,11]
];
var indexes2Keep = [0,2,6];
var slicedData = data.map(function (row){
return row.filter(function(_,i){
return indexes2Keep.indexOf(i) !== -1
})
})
//Alternatively
var slicedData2 = data.map(function (row){
return indexes2Keep.map(function(i){
return row[i]
})
})
console.log(slicedData)
console.log(slicedData2)
Simply call .map on that array to map each index to the element at that index in the row.
data.forEach(function(row) {
slicedData.push(indexes2Keep.map(function(index) {return row[index]}));
});
You could use the map() function for this:
slicedData.push(indexes2Keep.map(index => row[index]));

Remove duplicate index value from first array, manipulate second as per first(at some specific conditions)

This is the tricky one :
please understand my scenario:
I have two array , both array will have equal length always.
I want remove duplicate value in first array and second array will be manipulated according first one.
like if i have array like :
var firstArr = [1,1,4,1,4,5]
var secArr = ['sagar', 'vilas', 'suraj', 'ganesh','more','abhi']
//I want below Output
//[1,4,5] // this is firstArr after manipulation
//['sagar|vilas|ganesh','suraj|more',abhi] // this is secArr after manipulation
// here all duplicate values will be removed from first array
// and at same index second array will be manipulated.
please check my fiddle:
https://jsfiddle.net/abhilash503001/du4fe8ob/86/
You can use Map and reduce
First loop through the first array and map it values as key and take the values from second array's respective index as key
Now you have loop on the map's entries take the key's will be your unique firstArr and to get desired value for second arr you need to join values by |
var firstArray = [1,1,4,1,4,5]
var secArr = ['sagar', 'vilas', 'suraj', 'ganesh','more','abhi']
let op = firstArray.reduce((op,inp,index) => {
if(op.has(inp)){
let val = op.get(inp)
val.push(secArr[index])
op.set(inp, val)
} else {
op.set(inp,[secArr[index]])
}
return op
},new Map())
let {firstArr, secondArr} = [...op.entries()].reduce((op,[first,second])=>{
op.firstArr.push(first)
op.secondArr.push(second.join('|'))
return op
},{firstArr:[],secondArr:[]})
console.log(firstArr)
console.log(secondArr)
This is how I did it.
You first group the texts into arrays and then join them together.
var index_array = [1,1,4,1,4,5]
var text_array = ['sagar', 'vilas', 'suraj', 'ganesh','more','abhi'];
var manipulated_text_array = [];
var manipulated_index_array = [];
var groups = {};
for (let index in index_array) {
if (groups[index_array[index]] == undefined) {
groups[index_array[index]] = [];
}
groups[index_array[index]].push(text_array[index]);
}
for (let index in groups) {
manipulated_text_array.push(groups[index].join("|"));
}
manipulated_index_array = Object.keys(groups).map(x => parseInt(x));
console.log("texts", manipulated_text_array);
console.log("indexes", manipulated_index_array);

how can I find the lowest value in my array in JS?

I have the following code that calculates the highest value in my set of values:
var collection = [];
$histogram.find('li').each(function() {
collection.push($(this).data());
});
component.props.collection = collection;
// Find Histogram max value
collection.hasMax = function(value) {
return this.reduce(function(prev, curr) {
return prev[value] > curr[value] ? prev : curr;
});
};
// Assign Max Value
component.props.maxRange = collection.hasMax('value').value;
I need to create a second function that does the same, but for the lowest values, e.g. the function called hasMin. I thought it would be enough to just change the comparision here:
return prev[value] < curr[value] ? prev : curr;
but I tested it and it didn't work, can you help me with that?
JavaScript's built-in Math object has a static Math.min() method, which seems to solve your problem without the need for all that code you are using.
You can get the lowest value of an array by using JavaScript's destructuring assignment (to turn the array into a comma separated list of values) and pass that list to the method.
There's also Math.max().
let myData = [1,2,3,4,5,6,7,8,9,10];
console.log(Math.min(...myData));
console.log(Math.max(...myData));
You've indicated that collection is an array of objects and each object has a value property and you need to get the lowest and highest values in that object array so this will do it:
// This is just set up to emulate your data structure. Don't add this:
var sth = "test", sth2 = "test", sth3 = "test";
let component = { props: {} };
let collection = [{value:0, label: sth},{value:1, label: sth2},{value:3, label:sth3}];
// Assuming your data structure is set up, the following will get you there:
// Loop over the array of objects, extracting the value property of each object into a new array
let vals = collection.map(function(obj){
return obj.value; // Place the value of each object into an array
});
// Just set your object's properties to the min and max of the destructured array
component.props.minRange = Math.min(...vals);
component.props.maxRange = Math.max(...vals);
console.log(component.props.minRange, component.props.maxRange);
with ES5:
let sth = "test", sth2 = "test", sth3 = "test";
let component = { props: {} };
let collection = [{value:0, label: sth},{value:1, label: sth2},{value:3,
label:sth3}];
// Assuming your data structure is set up, the following will get you there:
// Loop over the array of objects, extracting the value property of each
object into a new array
let vals = collection.map(function(obj){
return obj.value; // Place the value of each object into an array
});
// Just set your object's properties to the min and max of the destructured array
component.props.minRange = Math.min.apply(Math,vals);
component.props.maxRange = Math.max.apply(Math,vals);
console.log(component.props.minRange, component.props.maxRange);

Comparing a given value against a multi-dimensional array

I really need your help.
I'd like to structure and build an array like the below.:
var provinces = [
['Ontario','ON'],
['Quebec','QC'],
['British Columbia','BC'],
['Saskatchewan','SK']
];
then, id like to compare the value (x) against my array, ie:
var x = 'Ontario'
if (x matches the value in the array list 'provinces') { then let x = ON }
How do you write something like this in javascript?
Much thanks and appreciation for all your help,
Use the .filter() function, that receives a true/false return condition to retrieve itens from an array:
var provinces = [
['Ontario','ON'],
['Quebec','QC'],
['British Columbia','BC'],
['Saskatchewan','SK']
];
var x = "Ontario";
//Find if any array item matches the word
var result = provinces.filter(function(item) {
return item[0] == x;
});
//If there's a match, get the second index from the first result from the filter
if(result.length > 0)
x = result[0][1];
alert(x);

Delete the array items which have lower specific value

I want to let array1 transform to array2.
The keyword is the test,test2,885,length.I want the keyword's next value(#?) to the next # is the highest.
var array1=["4#test#4#T#limited","6#test#6#885#restricted","7#test2#2#2#limited","8#test2#4#3#limited","11#885#1#TT#restricted","15#length#1#taw#restricted","17#885#11#T#limited"];
var arrar2=["6#test#6#885#restricted","8#test2#4#3#limited","17#885#11#T#limited","15#length#1#taw#restricted"];
Is this what you want?
var array1=["4#test#4#T#limited","6#test#6#885#restricted","7#test2#2#2#limited","8#test2#4#3#limited","11#885#1#TT#restricted","15#length#1#taw#restricted","17#885#11#T#limited"];
var keywords = ["test","test2","885","length"];
var array2 = [];
keywords.forEach(function (key) {
var matched = [];
var regex = new RegExp("\\b" + key + "#(\\d+)");
array1.forEach(function (value) {
if (regex.test(value)) {
matched.push([parseInt(RegExp.$1), value]);
}
});
if (matched.length > 0) {
matched.sort(function (a, b) {
return b[0] - a[0];
});
array2.push(matched[0][1]);
}
});
alert(array2);
JsFiddle example
You can use underscorejs to filter.
http://underscorejs.org/#filter
Then you can use javascript Array's sort method to sort the array if needed. You can pass a custom sorting function to sort. http://www.w3schools.com/jsref/jsref_sort.asp
The simplest way to "delete items from an array" based on the items fulfilling a condition is to use Array.prototype.filter (with the condition reversed).
In your case, it's rather hard to do because of how you organized your data (bundling it all in a string makes it hard to work with). Here is how i would work around it, but feel free to structure your data better from the start to avoid the awkward conversions:
var array1=["4#test#4#T#limited","6#test#6#885#restricted","7#test2#2#2#limited","8#test2#4#3#limited","11#885#1#TT#restricted","15#length#1#taw#restricted","17#885#11#T#limited"];
Make the data easier to work with by extracting the keyword and the value (i also keep some information to return to the original shape of the array):
var saneData = array1.map(function(item, index){
var split = item.split('#');
return {
keyword : split[1],
value: +split[0],
original : item,
originalIndex : index
}
});
Sort the data by the keyword (so all items with the same keywords go next to each other) and by the values (so the biggest value is first in a subset with the same keywords):
saneData.sort(function(a,b){
if (a.keyword !== b.keyword) {
return a.keyword.localeCompare(b.keyword);
} else {
return b.value - a.value;
}
});
Filter the array, keeping just the first item in a subset with the same keyword:
var filteredData = saneData.filter(function(item, index) {
if (index === 0) return true; // first item is good
return item.keyword !== saneData[index-1].keyword;
});
Return to the original form of the array (with the order preserved):
var array2 = filteredData.sort(function(a,b){ return a.originalIndex - b.originalIndex; }).map(function(item){ return item.original; });
// Result: ["6#test#6#885#restricted", "8#test2#4#3#limited", "15#length#1#taw#restricted", "17#885#11#T#limited"]

Categories

Resources