I have the following dynamically generated strings:
var stringA = ["a1", "a2", "a3" ... 'a400' ... 'a600']; // length 600
var stringB = ["b1", "b2", "b3" ... 'b400']; // length 400
How can I get an Array or string of both combined like this:
var myString = ["a1b1", "a2b2", "a3b3" ... "a400b400", "a401" ... "a600"]
You can do something like this:
var result = [], len = Math.max(stringA.length, stringB.length);
for(var i=0; i < len; i++) {
result.push((stringA[i] || "") + (stringB[i] || ""));
}
You can test it out here, the || "" is to prevent getting undefined as a string on the for the array that's shorter. The Math.max() call is to allow either A or B to be longer, it'll iterate to the end of either, just as A is longer in the question.
I don't think there's anything built into the Array object that will do it for you, you'll have to do the loop. The loop is trivial, though:
var index, length;
var result = [];
// assertion: arrayA.length === arrayB.length
result.length = arrayA.length; // Helps performance in some implemenations, harmless in others
for (index = 0, length = arrayA.length; index < length; ++index) {
result[index] = arrayA[index] + arrayB[index];
}
(I've renamed stringA -> arrayA and stringB -> arrayB to avoid confusion.)
If the arrays are different lengths or some of the entries in the arrays are undefined (which is totally possible, JavaScript arrays are sparse), you'll want to handle that in the loop, e.g.:
var index, length, Apresent, Bpresent;
var result = [];
result.length = Math.max(arrayA.length, arrayB.length); // Helps performance in some implementations, harmless in others
for (index = 0, length = result.length; index < length; ++index) {
Apresent = arrayA.hasOwnProperty(index);
Bpresent = arrayB.hasOwnProperty(index);
if (Apresent && Bpresent) {
result[index] = arrayA[index] + arrayB[index];
}
else if (Apresent) {
result[index] = arrayA[index];
}
else if (Bpresent) {
result[index] = arrayB[index];
}
}
If the arrays are sparse and they both happen to be sparse at the same index, the resulting array will also be sparse.
If you do not need to retain the the items in the original 2 arrays then the code below works really well. It does not have a predetermined limit to the number of iterations in the for loop which means that the stringA and StringB array could continue to grow in size while this code is running.
var myString = [];
for(var answer; answer = (stringA.shift() || "") + (stringB.shift() || "");) {
myString.push(answer);
}
var myString = [];
for (var i=0;i<stringA.length;i++){
myString[i] = stringA[i] + stringB[i];
}
Related
Let's say that I'm doing this because of my homework. I would like to develop some kind of schedule for the week to come (array of 6-7 elements - output result). But I have one problem. I need to figure it out how one element be positioned in the array and also his frequency must be exactly what user input is. Elements must be positioned at different index in the array.
I'm having that kind of input from user (just an example);
var arrayOfElements = ["el1","el2","el3"];
var el1Frequency = 3;
var el2Frequency = 2;
var el3Frequency = 1;
//output array of schedule (this is just an example)
var finaloutPutArray = ["el1","el2","el3","el1","el2","el1"];
Index of elements el1 is 0, 3 and 5, basically, I don't want elements to be repeated like this;
["el1","el1","el2","el3"...];
["el2","el1","el1","el3"];
Can you please give me some ideas on how to solve this problem.
I started like this;
var finalSchedule = [];
var totalDaysPerWeek = 6;
for(var i =0; i < totalDaysPerWeek; i++) {
...
}
This is one pattern, check my working snippet:
var arrayOfElements = ["el1","el2","el3"];
var obj = { el1: 3,
el2: 2,
el3: 1};
// First determine the max recurring of an element, this will be the number of cycles fo your loop
// Check key values
var arr = Object.keys(obj).map(function ( key ) { return obj[key]; });
// Get max value
var max = Math.max.apply( null, arr );
var finalArray = [];
// Iterate from 0 to max val
for(i = 0; i < max; i += 1){
// Iterate on array of elements
for(k = 0; k < arrayOfElements.length; k += 1) {
// If config of recurring
if( obj[arrayOfElements[k]] >= i+1 ) {
// Push into array
finalArray.push(arrayOfElements[k]);
}
}
}
console.log(finalArray);
I am working on this piece of code here where the goal is to create an array of all the values that are duplicated from another array. The resulting array I'd like to have should only enter the duplicated values from the first array once. The catch is I can't use any array functions or methods. This is what I have so far:
var numbers = [8,24,20,5,13,3,1,12,11,24,8,24,20,4,5,23,24,23,21,2,19,3,21,2,14,17,21,5,7,10,20,11,0,5,18,2,13,11,14,3,20,1,23,6,21,10,14,0,15,20];
var results = [];
var tempArr = [];
for (var i = 0; i <= numbers.length; i++) {
if (tempArr[numbers[i]] === undefined) {
tempArr[numbers[i]] = 1;
} else if (results[numbers[i]] === undefined) {
results.push(numbers[i]);
}
}
console.log(tempArr);
console.log(results);
I am getting closer to me desired output… but for some reason the results array continues to contain multiple entries of the values that are duplicated in the numbers array. Where am I going wrong here?
You're basically abusing an array as an object. Try using an object instead to log your values (and give said object a name that represents what it holds), it'll greatly simplify your code:
var numbers = [8,24,20,5,13,3,1,12,11,24,8,24,20,4,5,23,24,23,21,2,19,3,21,2,14,17,21,5,7,10,20,11,0,5,18,2,13,11,14,3,20,1,23,6,21,10,14,0,15,20];
var results = [];
var seenValues = {};
for (var i = 0; i < numbers.length; i++) {
const number = numbers[i];
seenValues[number] = 1 + (seenValues[number] || 0);
// check to see if it's been seen exactly once before,
// so that the duplicated value is only added once:
if (seenValues[number] === 2) results[results.length] = number;
}
//console.log(seenValues);
console.log(results);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Array value count javascript
I have an array which contains several duplicates, what I'm trying to achieve is to count how many duplicates each unique string has in this one array.
The array looks something like this
array = ['aa','bb','cc','aa','ss','aa','bb'];
Thus I would like to do something like this
if (xWordOccurrences >= 5) {
// do something
}
But I'm not sure how I would code this.
I was thinking, create an object with each unique string, then loop through the original array, match each string with it's object and increment it's number by 1, then loop over the object to see which words had the most duplicates...
But this seems like an over complexe way to do it.
You can use an object which has keys of the Array's values and do something like this
// count everything
function getCounts(arr) {
var i = arr.length, // var to loop over
obj = {}; // obj to store results
while (i) obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
return obj;
}
// get specific from everything
function getCount(word, arr) {
return getCounts(arr)[word] || 0;
}
getCount('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
If you only ever want to get one, then it'd be more a bit more efficient to use a modified version of getCounts which looks similar to getCount, I'll call it getCount2
function getCount2(word, arr) {
var i = arr.length, // var to loop over
j = 0; // number of hits
while (i) if (arr[--i] === word) ++j; // count occurance
return j;
}
getCount2('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
Try this function:
var countOccurrences = function(arr,value){
var len = arr.length;
var occur = 0;
for(var i=0;i<len;i++){
if(arr[i]===value){
occur++;
}
}
return occur;
}
var count = countOccurrences(['aaa','bbb','ccc','bbb','ddd'],'bbb'); //2
If you want, you can also add this function to the Array prototype:
Array.prototype.countOccurrences = function(value){
var len = this.length;
var occur = 0;
for(var i=0;i<len;i++){
if(this[i]===value){
occur++;
}
}
return occur;
}
How about you build an object with named property?
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var summary = {};
var item = '';
for ( i in array){
item = array[i];
if(summary[item]){
summary[item] += 1;
}
else{
summary[item] = 1;
}
}
console.log( summary );
summary will contain like this
{aa: 3, bb: 2, cc: 1, ss: 1}
which you could then iterate on and then sort them later on if needed.
finally to get your count, you could use this summary['aa']
<script type="text/javascript">
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var myMap = {};
for(i = 0; i < array.length; i++) {
var count = myMap[array[i]];
if(count != null) {
count++;
} else {
count = 1;
}
myMap[array[i]] = count;
}
// at this point in the script, the map now contains each unique array item and a count of its entries
</script>
Hope this solves your problem
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var dups = {};
for (var i = 0, l = array.length; i < l; i++ ) {
dups[array[i]] = [];
}
for (str in dups) {
for (var i = 0, l = array.length; i < l; i++ ) {
if (str === array[i]) {
dups[str].push(str);
}
}
}
for (str in dups) {
console.log(str + ' has ' + (dups[str].length - 1) + ' duplicate(s)');
}
This function may do everything you need.
function countDupStr(arr, specifier) {
var count = {}, total = 0;
arr.forEach(function (v) {
count[v] = (count[v] || 0) + 1;
});
if(typeof specifier !== 'undefined') {
return count[specifier] - 1;
}
Object.keys(count).forEach(function (k) {
total += count[k] - 1;
});
return total;
}
Each value in the array is assigned and incremented to the count object. Whether or not a specifier was passed, the function will return duplicates of that specific string or the total number of duplicates. Note that this particular technique will only work on string-coercible values inside your arrays, as Javascript can only index objects by string.
What this means is that during object assignment, the keys will normalize down to strings and cannot be relied upon for uniqueness. That is to say, this function wouldn't be able to discern the difference between duplicates of 3 and '3'. To give an example, if I were to perform:
var o = {}, t = {};
o[t] = 1;
console.log(o);
The key used in place of t would eventually be t.toString(), thus resulting in the perhaps surprising object of {'[object Object]': 1}. Just something to keep in mind when working with Javascript properties.
I saw this post about it, perhaps it can help:
http://ryanbosinger.com/blog/2011/javascript-count-duplicates-in-an-array/
I have an array that looks like this:
1. coordinates = [ [16.343345, 35.123523],
2. [14.325423, 34.632723],
3. [15.231512, 35.426914],
4. [16.343345, 35.123523],
5. [15.231512, 32.426914] ]
The latitude on line 5 is the same as on line 3, but they have different longitudes and are therefore not duplicates.
Both the latitude and longitude are the same on line 3 and 6, and are therefore duplicates and one should be removed.
The difficulty in this question that different arrays never compare equal even if they contain same values. Therefore direct comparison methods, like indexOf won't work.
The following pattern might be useful to solve this. Write a function (or use a built-in one) that converts arrays to scalar values and checks if these values are unique in a set.
uniq = function(items, key) {
var set = {};
return items.filter(function(item) {
var k = key ? key.apply(item) : item;
return k in set ? false : set[k] = true;
})
}
where key is a "hash" function that convert items (whatever they are) to comparable scalar values. In your particular example, it seems to be enough just to apply Array.join to arrays:
uniqueCoords = uniq(coordinates, [].join)
You can use standard javascript function splice for this.
for(var i = 0; i < coordinates.length; i++) {
for(var j = i + 1; j < coordinates.length; ) {
if(coordinates[i][0] == coordinates[j][0] && coordinates[i][1] == coordinates[j][1])
// Found the same. Remove it.
coordinates.splice(j, 1);
else
// No match. Go ahead.
j++;
}
}
However, if you have thousands of points it will work slowly, than you need to consider to sort values at first, then remove duplicates in one loop.
I rewrote the answer from thg435 (It does not allow me to post comments) and prototype it also using jQuery instead, so this will work on all browsers using it (Even IE7)
Array.prototype.uniq = function (key) {
var set = {};
return $.grep(this, function (item) {
var k = key
? key.apply(item)
: item;
return k in set
? false
: set[k] = true;
});
}
You can use it like:
arr = arr.uniq([].join);
If you are not on Safari this single liner could do the job
var arr = [[16.343345, 35.123523],
[14.325423, 34.632723],
[15.231512, 35.426914],
[16.343345, 35.123523],
[15.231512, 32.426914]],
lut = {},
red = arr.filter(a => lut[a] ? false : lut[a] = true);
document.write("<pre>" + JSON.stringify(red,null,2) + "</pre>");
It might be simpler to create another array keeping only unique coordinate pairs
var uniqueCoors = [];
var doneCoors = [];
for(var x = 0; x < coordinates.length; x++) {
var coorStr = coordinates[x].toString();
if(doneCoors.indexOf(coorStr) != -1) {
// coordinate already exist, ignore
continue;
}
doneCoors.push(coorStr);
uniqueCoors.push(coordinates[x]);
}
function sortCoordinates(arr){
var obj = {};
for(var i = 0, l = arr.length; i < l; i++){
var el = arr[i];
var lat = el[0];
var lng = el[1];
if(!obj[lat + lng]){
obj[lat + lng] = [lat, lng];
}
}
var out = [];
for(p in obj){
out.push([obj[p][0], obj[p][1]]);
}
return out;
}
I am not sure about coordinates[][] dataType. Make the comparison accordingly.
var dubJRows= new Array();
for(int i = 0; i < coordinates.length -2; i++){
for(int j = i+1; j < coordinates.length -1; j++){
if (i != j && chk_dubJRows_not_contains(j)) {
innerArray1 [1][1] = coordinates[i];
innerArray2 [1][1] = coordinates[j];
if ( innerArray1 [1][0] == innerArray2[1][0]
&& innerArray1[1][1] == innerArray2[1][1]) {
dubJRows.push(j);
}
}
}
}
//REMOVE ALL dubJRows from coordinates.
I have a array like
arr[1] = 234;
arr[2] = 345;
...
arr[40] = 126;
How can I get the index of the element with the highest value without reiterating the array?
You can apply Math.max and pass the array as its arguments-
arr.indexOf(Math.max.apply(window,arr))
But now Math.max is doing the iterating, just as sort would do.
Somebody has to look at each item in an unsorted array...
With jQuery, is as simple as:
// Get the max value from the array
maxValue = Math.max.apply(this, arr);
// Get the index of the max value, through the built in function inArray
$.inArray(maxValue,arr);
If the array is not ordered you cannot do this without iterating.
Get the array key with the highest value in javascript
var cars = ["Saab", "Volvo", "BMW"];
var max_car_result = cars[cars.length-1];
alert(max_car_result);
Try this:
var max_index = -1;
var max_value = Number.MIN_VALUE;
for(var i = 0; i < arr.length; i++)
{
if(arr[i] > max_value)
{
max_value = arr[i];
max_index = i;
}
}
You could use a function to set the variable. And keep track of the max in that function. Here's a quick example without type checking, testing, or support for removing a value.
Array.prototype.maxValue = null;
Array.prototype.setIndex = function(index, value){
this[index] = value;
if (value > this.maxValue || this.maxValue == null)
this.maxValue = value;
}
var arr = new Array();
arr.setIndex(0, 234);
arr.setIndex(1, 500);
arr.setIndex(2, -5);
var maxValue = arr.maxValue;
Obviously this is nicer if you're currently setting items like this:
var arr = new Array();
arr[0] = 1;
arr[1] = 500;
arr[2] = 2;
Rather than this:
var arr = { 1, 500, 2 };
The downside is its not natural and requires you to use function to get the correct results.
Keep the array sorted or use a heap.
Otherwise iterate. Even if you found some trick to do it it would still require iterating underneath so why not iterate?
If it seems like too much code, put it in a separate routine.
Two solution: to sort descending order and get the first element or:
function bigger(array) {
if (array.length < 1) {
return -1;
}
bigger = 0;
for(var i=1; i<array.length;i++ ) {
if(array[i] > array[bigger]) {
bigger = i;
}
}
return bigger;
}
you cold optimize using two variables, one for the position and other for the content.
Either you will have iteration somewhere (in your code or in JQuery.each()) or you can define something like this:
Array.prototype.mpush = function(v)
{
var maxv = this.maxValue || Number.MIN_VALUE;
if( v > maxv ) { this.maxValue = v; this.maxIndex = this.length; }
this.push(v);
}
and use that arr.mpush(v) to populate your array. In this case the array will have maxIndex property.
Is old question but here is an my simple emulation of PHP script max() made in javascript:
function max(array){
if(Object.prototype.toString.call( array ) === '[object Array]'){
return array[(array.length-1)];
}
else return 0;
}
This return value of last key in array or 0 if nothing found.
Maby someone helps.
You can use it like:
var array = ['bananaman','spiderman','ironman','superman','batman','manman'];
var getLast = max(array);
if(getLast !== 0)
alert(getLast); // manman