Join Array from startIndex to endIndex - javascript

I wanted to ask if there is some kind of utility function which offers array joining while providing an index. Maybe Prototype of jQuery provides this, if not, I will write it on my own :)
What I expect is something like
var array= ["a", "b", "c", "d"];
function Array.prototype.join(seperator [, startIndex, endIndex]){
// code
}
so that array.join("-", 1, 2) would return "b-c"
Is there this kind of utility function in an pretty common Javascript Library?
Regards
globalworming

It works native
["a", "b", "c", "d"].slice(1,3).join("-") //b-c
If you want it to behave like your definition you could use it that way:
Array.prototype.myJoin = function(seperator,start,end){
if(!start) start = 0;
if(!end) end = this.length - 1;
end++;
return this.slice(start,end).join(seperator);
};
var arr = ["a", "b", "c", "d"];
arr.myJoin("-",2,3) //c-d
arr.myJoin("-") //a-b-c-d
arr.myJoin("-",1) //b-c-d

Just slice the array you want out, then join it manually.
var array= ["a", "b", "c", "d"];
var joinedArray = array.slice(1, 3).join("-");
Note: slice() doesn't include the last index specified, so (1, 3) is equivalent to (1, 2).

Related

sort function unexpected behaviour

i am trying to understand array sorting method , the problem i am currently facing is when i am declaring some variables inside compare function its not sorting the same as it is doing without those variables although those variables are not used anywhere
can anyone explain what is actually happening here
also i find out that sort functions behave different in firefox and chrome
page_link i am testing this in firefox dev edition
let list1 = ["a","b","c","d","e","f","g","h","i"]
list1.sort((a,b)=>{
let pat = ["d","a"]
return b - a
})
console.log(list1) // Array(9) [ "a", "b", "c", "d", "e", "f", "g", "h", "i" ]
let list2 = ["a","b","c","d","e","f","g","h","i"]
list2.sort((a,b)=>{
// let pat = ["d","a"]
return b - a
})
console.log(list2) // Array(9) [ "i", "h", "g", "f", "e", "d", "c", "b", "a" ]
If you do "a" - "b" it evaluates to NaN which is incorrect as that's not what you intended and also inconsistent (varies browser to browser).
Either don't pass a callback to sort in which case it does the following:
The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
Or you can use String.prototype.localeCompare
let list = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
console.log([...list].sort());
console.log([...list].sort((a, b) => a.localeCompare(b)));
If you want to prepend some values to the sorted array you'll have to do it separately you can't do it using sort.
let list = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
let pat = ["x", "y"];
let sortedList = [...list].sort();
let patAppendedSortedList = [...pat, ...sortedList];
console.log(patAppendedSortedList);
And if you want to sort both the list and pat but you want to keep all pat elements before all list elements then consider the snippet below.
let list = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
let pat = ["z", "x", "y"];
let patSet = new Set(pat);
let sortedList = [...pat, ...list].sort((a, b) => {
// If a has higher priority put it before b
if (patSet.has(a) && !patSet.has(b)) {
return -1;
}
// If b has higher priority put it before a
if (patSet.has(b) && !patSet.has(a)) {
return 1;
}
// Otherwise both a and b have same priority
// Sort them according to their value
return a.localeCompare(b);
});
console.log(sortedList);
If you subtract a string from another string, it will attempt to convert the strings to numbers.
All of your strings will convert to NaN.
NaN-NaN is also NaN.
So it doesn't matter which two values from your array you are comparing, your comparison function will always return NaN.
(Note that a comparison function is supposed to return a number that is 0, greater than 0 or less than 0 and be consistent for any given pair of values. The one you are using is just broken for the data you are using).
The order the letters get sorted into therefore depends on the order in which they are compared to each other (because your comparison function is broken).
That order is determined by the sort algorithm that the JS engine uses. This is an implementation detail that the specification doesn't mandate.
One browser might use a quick sort while another might use a bubble sort. Hence you get different results.
Write a comparison function which isn't nonsense to get consistent results.
The default comparison function is find for lexical sorting under most circumstances.
Now i understood your goal. But you cant archive this with your way. You cant make some prepends of values in the JS sort function. You have to make it in two steps. 1.) sort 2.) prepend your pat values to the sorted array.
const list = ["a","b","c","d","e","f","g","h","i"];
const pat = ["d","a"];
const sorted = [...pat, ...list.sort()];
console.log(sorted)

Remove first occurence of an element using JavaScript or Lodash

I have an array like this -
["a", "a", "b", "c", "d", "e"]
I want to operate on this and filter it to remove only the first occurence of every element in the array.
The output in the above case is expected to be - ["a"]
How can I achieve this using JavaScript or Lodash?
By wanting the first one of duplicate following items, you could use Array#lastIndexOf along with a check of the actual index.
const
data = ["a", "a", "b", "c", "d", "e"],
result = data.filter((v, i, a) => i !== a.lastIndexOf(v));
console.log(result);
You can use an empty object as a map to easily check if the item has been found before and then use Array#filter to remove the ones you don't want.
var list = ["a", "a", "b", "c", "d", "e"];
var occurences = {};
var filteredList = list.filter(function(item) {
if (item in occurences) return true; // if it has already been registered, add it to the new list
occurences[item] = 1; // register the item
return false; // ignore it on the new list
});
console.log(filteredList);
Shorthand version
let list = ["a", "a", "b", "c", "d", "e"], occurences = {};
list = list.filter(item => item in occurences ? 1 : occurences[item] = 1 && 0);
console.log(list);
you can simply use shift method checkout it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

Sort an array of strings based on an array of numbers: Another version (Not duplicate!!) [duplicate]

This question already has answers here:
Reorder the objects in the array
(5 answers)
Closed 2 years ago.
I know I uploaded a similar question, but my intention is different here so this is not a duplicate question.
I want to sort an array based on another array of numbers. More specifically, if 1 is the nth element of the array of numbers, I want to rearrange the target array so that the nth element in the original array is the first element, and so on. For example;
//Case 1
const input = ["a", "b", "c", "d", "e"];
const order = [2, 4, 5, 1, 3];
intended_result: ["d", "a", "e", "b", "c"];
//Case 2
const input = ["a", "b", "c", "d", "e"];
const order = [3, 1, 4, 5, 2];
intended_result: ["b", "e", "a", "c", "d"];
What would be the Javascript code to do the above operation? Any suggestion?
Thanks a lot in advance!
No need for sorting, you just need to apply the permutation that you have:
const result = [];
for (let i=0; i<order; i++)
result[order[i]-1] = input[i];
This should be working:
const sorted = input.slice().sort((a, b) => {
const indexA = input.indexOf(a);
const indexB = input.indexOf(b);
return order[indexA] - order[indexB];
});
We slice the input so it won't be mutated and change the index of values in the array.

Shorthand for creating an array of string values in javascript

Is there a quick way to create a literal array filled with strings in javascript?
I am coming from Ruby, where using %w{} allows for you to omit quotation marks and commas around the values of the array. For example:
array = %w{a b c}
=> ["a", "b", "c"]
is equivalent to the standard syntax for literal assignment:
array = ["a", "b", "c"]
=> ["a", "b", "c"]
Is there anything similar to this in javascript?
There may be a better way, but this would work:
var array = 'abc'.split(''); // ['a', 'b', 'c']
And for words:
var array = 'domo arigato mr. roboto'.split(' ');
// ['domo', 'arigato', 'mr.', 'roboto']
I don't know it's a proper way or not but I go with
'abc'.split(''); //returns array

Javascript some() method and additional parameter

I need to check if at least one element in an array pass a condition.
The condition depends on a variable.
For example, I'm using something like this:
function condition(previousValue, index, array) {
return additonalValue.indexOf(previousValue) + previousValue.indexOf(additonalValue) < -1;
}
I can't figure out how can I pass the "additonalValue" parameter to the array.some(condition) expression.
I'm using jQuery so, an alternative for it is welcome.
Is there a way to pass a parameter to array.some() method?
If you want to pass an additional parameter to the function that is placed inside the some method you can use bind.
var myArray = ['a', 'b', 'c', 'd'];
var otherValue = 'e';
function someFunction(externalParameter, element, index, array) {
console.log(externalParameter, element, index, array);
return (element == externalParameter);
}
myArray.some(someFunction.bind(null, otherValue));
This would give you:
e a 0 ["a", "b", "c", "d"]
e b 1 ["a", "b", "c", "d"]
e c 2 ["a", "b", "c", "d"]
e d 3 ["a", "b", "c", "d"]
false
Using a closure looks like the simplest solution :
var additonalValue = 79;
var r = myArray.some(function(previousValue) {
return additonalValue.indexOf(previousValue) + previousValue.indexOf(additonalValue) < -1;
});
The some() function accepts additional arguments in the form of an array, that is set to this inside the callback, so you could pass a number of values that way :
var arr = ['one', 'two', 'three'];
var val = 'two';
var r = arr.some(function(value) {
return this[0] == value;
}, [val]);
FIDDLE

Categories

Resources