0

i have an array like [x/0/2 , x/0/3 , y/3/1 , x/1/1 , x/0/3 , x/1/2],

i need to convert the elements range like [x/0/2-3 , y/3/1 , x/1/1-2] Please give some suggestion for this.

2
  • 2
    What is x/0/2, etc.? Commented Oct 26, 2019 at 11:35
  • 1
    Please provide an MVCE of your problem. Start with what you have tried so far. Also helpful would be an in-depth explanation of the rules/logic you applied to get from the first array to the second. Commented Oct 26, 2019 at 11:38

2 Answers 2

1

Use reduce to iterate over the array and create an object grouped by the element root, then use Object.entries to pull out the correct information from the object.

const arr = ['x/0/2', 'x/0/3', 'y/3/1', 'x/1/1', 'x/0/3', 'x/1/2'];

const out = arr.reduce((acc, c) => {

  // `split` out the separate parts of the element 
  const [ root1, root2, index ] = c.split('/');

  // We'll use the first two parts as the object key
  const key = `${root1}/${root2}`;

  // If the key doesn't already exist create an empty
  // array as its values
  acc[key] = acc[key] || [];

  // To prevent duplicates only add an index if it
  // isn't already in the array
  if (!acc[key].includes(index)) acc[key].push(index);

  // Return the accumulator for the next iteration
  return acc;
}, {});

// Then iterate over the object entries with `map`
const result = Object.entries(out).map(([ key, values ]) => {

  // Return the joined up value
  return `${key}/${values.join('-')}`;
});

console.log(result);

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for support andy. But expectations is, If suppose my array is['x/0/2', 'x/0/3', 'y/3/4','y/3/9','x/1/1', 'x/1/2'] answer getting like ["x/0/2-3", "y/3/4-9", "x/1/1-2"] as per your code, but in this we don't have 'y/3/5','y/3/6','y/3/7','y/3/8' values range. the output should be ["x/0/2-3", "y/3/4","y/3/9", "x/1/1-2"] like this.
I could only create output based on the input you provided in your question. I have no idea what that other range of inputs does.
0

If I understand your question, you could create an array within the array to hold the range of values. Checking if the position in the array is an actual array let’s you know there are values that span a range within.

Example:

var values = [x/01, [x/20, x/21, x/22], x/03]

You could also create an object that could accomplish something similar depending on your needs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.