sort array by specific pattern [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to get the array from:
const foo = [
FOO_BAR_A_READ_SELF,
FOO_BAR_A_WRITE_SELF,
FOO_BAR_A,
FOO_BAR_A_READ_ALL,
FOO_BAR_A_WRITE_ALL,
FOO_BAR_B_READ_SELF,
FOO_BAR_B_WRITE_SELF,
FOO_BAR_B,
FOO_BAR_B_READ_ALL,
FOO_BAR_B_WRITE_ALL
]
to
const foo = [
FOO_BAR_A,
FOO_BAR_A_READ_SELF,
FOO_BAR_A_WRITE_SELF,
FOO_BAR_A_READ_ALL,
FOO_BAR_A_WRITE_ALL,
FOO_BAR_B,
FOO_BAR_B_READ_SELF,
FOO_BAR_B_WRITE_SELF,
FOO_BAR_B_READ_ALL,
FOO_BAR_B_WRITE_ALL
]
i tried to go with the length by splitting with the "_", but I never worked with the sort function that specific.
I only used desc and asc ( return 1 > -1 ) || ( return -1 > 1 )
Can someone can explain me how I can get the wanted result?

Not sure it was my best...
var arr = [
'FOO_BAR_A_WRITE_SELF',
'FOO_BAR_A',
'FOO_BAR_A_READ_SELF',
'FOO_BAR_A_READ_ALL',
'FOO_BAR_A_WRITE_ALL',
'FOO_BAR_B_READ_SELF',
'FOO_BAR_B_WRITE_SELF',
'FOO_BAR_B',
'FOO_BAR_B_READ_ALL',
'FOO_BAR_B_WRITE_ALL'
];
const onRWorder=s=>{
let x = s.replace('_WRITE_','_')
if (x != s) x += '_WRITE'
else {
x = s.replace('_READ_','_')
if (x!= s) x += '_READ'
}
return x
}
arr.sort(function(a, b){
let a1 = onRWorder(a)
let b1 = onRWorder(b)
if(a1 < b1) { return -1 }
if(a1 > b1) { return 1 }
return 0
})
for (let z of arr) console.log(z)
.as-console-wrapper { max-height: 100% !important }

did you try this ?
var arr = [
'FOO_BAR_A_WRITE_SELF',
'FOO_BAR_A',
'FOO_BAR_A_READ_SELF',
'FOO_BAR_A_READ_ALL',
'FOO_BAR_A_WRITE_ALL',
'FOO_BAR_B_READ_SELF',
'FOO_BAR_B_WRITE_SELF',
'FOO_BAR_B',
'FOO_BAR_B_READ_ALL',
'FOO_BAR_B_WRITE_ALL'
];
var sorted = arr.sort();
console.log(sorted);

Related

how to check if value exists from value? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
if I have the following values
0 - a
1 - b
2 - c
4 - d
8 - e
16 - f
if i get the value 17, how would i know that values b and f are in that values, some for the others as these can be mixed together by adding, so bd value would be 6
Convert your value to binary format. For example 17 => 10001. Then select only 1's. You can make for loop starts from 'a' to 'z'. Increase characters +1 then convert to character.
This is sample code:
function foo(num) {
if (num == 0)
return 'a';
const binaryNum = (num >>> 0).toString(2);
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
var converted = '';
var asci = 'b';
for(var i=binaryNum.length-1; i>=0; --i) {
if (binaryNum.charAt(i) == '1')
converted+=asci;
asci = nextChar(asci);
}
return converted;
}
console.log(foo(17));
console.log(foo(0));
console.log(foo(6));
console.log(foo(28));
Output is:
bf
a
bd
def
Note that 'bd' is 5.
Much like the bank note problem, reduce down the value in denominations, then pick out the index for the map to the letter.
const v1 = [0, 1, 2, 4, 8, 16];
const v2 = ['a', 'b', 'c', 'd', 'e', 'f'];
let value = 7
const vMap = new Map();
for (let i = v1.length - 1; i >= 0 && value; i--) {
const qty = Math.floor(value / v1[i]);
qty && vMap.set(v1[i], qty);
value = value % v1[i];
}
const entries = Array.from(vMap.entries());
console.log(entries.map(([curr, qty]) => `${curr} * ${qty} = ${curr * qty} is ${v2[v1.indexOf(curr)]}`))

get the specific index of element in the array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a list of different units:
const unitList = [1, 10, 36, 50, 20]; // all different numbers and all numbers are above 0
const unit = 13; // this is not included in unitList and not more that max number in unitList
And I want to get the index of unit in which unit should be placed before. for instance:
const unit = 13; returns index 4 because it should be placed before 20
const unit = 35; returns index 2 because it should be placed before 36
function getUnitPosition() {
if(!unitList.length) return 'before add new unit';
const max = Math.max(...unitList);
if(unit > max) return 'before add new unit';
const min = Math.min(...unitList);
if(unit < min) return columns[0].id;
for(let a = 0; a < unitList.length; a++) {
console.log(unit , unitList[a], unit < unitList[a])
if(unit < unitList[a]) return columns[a].id;
}
}
You could take the first found index with a smaller value than unit. For any other smaller value check the value to get the smallest one.
const
getIndex = (data, unit) => {
let index;
for (let i = 0; i < data.length; i++) {
if (
unit < data[i] &&
(index === undefined || data[i] < data[index])
) index = i;
}
return index;
},
unitList = [1, 10, 36, 50, 20];
// 13 ^^
// 35 ^^
console.log(getIndex(unitList, 13)); // 4 placed before 20
console.log(getIndex(unitList, 35)); // 2 placed before 36

Want to Sort with Loop In JS [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
let fruits = [mango,banana,avocado,apple,orange,lychee];
let prices = [50,90,65,300,600,900]; // not constant value;
//Solution with If else
if(prices > 0 && prices <= 50) console.log("Mango#0-50")
if(prices > 51 && prices <= 65)console.log("Mango#0-50<br>Banana#51-65")
//So on
Is there any way to short it with loop?
This is how the result should look like
Mango#0-50
Banana#51-65
avocado#65-90
apple#91-300
orange#301-600
lychee#601-900
rest#>901
Note: I do not want to use If else;
let i = 1
fruits.map(fruit => `${fruit.name}#${i}-${i+=100}`);
You could map the fruits with their price range and slice the array by the wanted length and return a joined string.
function getValues(price) {
return temp
.slice(0, (prices.findIndex(p => price <= p) + 1) || prices.length + 1)
.join('<br>');
}
const
fruits = ['mango', 'banana', 'avocado', 'apple', 'orange', 'lychee'],
prices = [50, 90, 65, 300, 600, 900].sort((a, b) => a - b),
temp = [...fruits.map((f, i, { length }) => `${f}#${prices[i - 1] + 1 || 0}-${prices[i]}`), `rest#>${prices[prices.length - 1] + 1}`];
console.log(getValues(100));
console.log(getValues(300));
console.log(getValues(301));
console.log(getValues(1000));

Increase values of elements in an array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Say I have an array like so...
let myArr = [0,0,2,0,0];
I want to create sort of a ripple effect such that the result of the array is [0,1,2,1,0]
This would give you the result you expect:
let myArr = [0, 0, 2, 0, 0];
createRippleArray = (myArr) => {
if (myArr.length % 2 === 0) {
console.error("createRippleArray: Array length needs to be odd number>1");
return [];
}
let midIndex = ~~(myArr.length / 2);
let mid = myArr[midIndex];
return myArr.map((e, i) => {
let res;
if (i < midIndex) {
return ~~(mid / Math.abs(midIndex - i + 1));
} else if (i === midIndex) {
return mid;
} else if (i > midIndex) {
return ~~(mid / Math.abs(midIndex - i - 1));
}
});
}
console.log(createRippleArray(myArr));
Hope this helps!

Why this solution can't use a for-loop? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I was donig Intersection of Two Arrays II in leetcode.
I found solution in it and one thing that i don't understand is
Why this solution can't use for loop?
if i changed this line of code
while(p1 < nums1.length && p2 < nums2.length)
into
for(let p1=0,let p2=0;p1 < nums1.length && p2 < nums2.length;p1++;p2++)
the output will changed to only [2] not [2,2]
Why is that happened?
Request:
Given two arrays, write a function to compute their intersection.
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Here is the JS code:
var intersect = function(nums1, nums2) {
nums1.sort(cm);
nums2.sort(cm);
var p1 =0
var p2 =0
var res = [];
while(p1 < nums1.length && p2 < nums2.length) {
if(nums1[p1] === nums2[p2]) {
res.push(nums1[p1]);
p1++;
p2++;
} else if(nums1[p1] > nums2[p2]) {
p2++;
} else {
p1++;
}
}
return res;
};
var cm = function(a, b) {
return a - b;
}
console.log(intersect([1,2,2,1], [2,2]))
Consider the following for loop
for(let p1=0,let p2=0;p1 < nums1.length && p2 < nums2.length;p1++;p2++)
In this p1 and p2 always get increased in every loop. But in you you original code. There are increased conditionally
Why for loop returns `[2]`:
When you increase p1 and p2 initially setting them to 0. So it means
in every loop the p1=p2. And hence it will compare the values on same indexes.
In the following two arrays.
[1,2,2,1]
[2,2]
Only the second 2 ([1,2,2,1] [2,2]) will be matched because both have same index 1.
else if(nums1[p1] > nums2[p2]) {
p2++;
} else {
p1++;
}
You can also do that using filter() and includes()
const intersect = (num1,num2) => num1.filter(x => num2.includes(x))
console.log(intersect([1,2,2,1],[2,2]))

Categories

Resources